<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/10/20
 * Time: 10:39
 */
namespace App\Api\Controllers\WinCode;


use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayTradeFastpayRefundQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeRefundRequest;
use App\Api\Controllers\Config\MerchConfigController;
use App\Api\Controllers\Config\WingConfigController;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Api\Controllers\Config\EasyPayConfigController;
use App\Api\Controllers\Config\HConfigController;
use App\Api\Controllers\Merchant\OrderController;
use App\Common\RefundSuccessAction;
use App\Services\Pay\GuoTonXinYi\BizService;
use App\Services\Pay\PayService;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Api\Controllers\Config\AbcConfigController;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use App\Api\Controllers\Config\HkrtConfigController;
use App\Api\Controllers\Config\JiuJiangConfigController;
use App\Api\Controllers\Config\HuiPayConfigController;
use App\Api\Controllers\Config\HwcPayConfigController;
use App\Api\Controllers\Config\JdConfigController;
use App\Api\Controllers\Config\LianfuConfigController;
use App\Api\Controllers\Config\LianfuyoupayConfigController;
use App\Api\Controllers\Config\LinkageConfigController;
use App\Api\Controllers\Config\LtfConfigController;
use App\Api\Controllers\Config\MyBankConfigController;
use App\Api\Controllers\Config\NewLandConfigController;
use App\Api\Controllers\Config\TfConfigController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\Config\WeixinConfigController;
use App\Api\Controllers\Config\SaobeiConfigController;
use App\Api\Controllers\Config\CoolConfigController;
use App\Api\Controllers\Config\PinganConfigController;
use App\Api\Controllers\Config\WftPayConfigController;
use App\Api\Controllers\DuoLaBao\ManageController;
use App\Api\Controllers\MyBank\TradePayController;
use App\Api\Controllers\Config\AllinpayConfigController;
use App\Api\Controllers\Newland\PayController;
use App\Api\Controllers\Linkage\PayController as LinkagePayController;
use App\Api\Controllers\WftPay\PayController as WftPayPayController;
use App\Api\Controllers\HwcPay\PayController as HwcPayPayController;
use App\Common\PaySuccessAction;
use App\Models\AlipayAppOauthUsers;
use App\Models\AlipayIsvConfig;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Shop;
use App\Models\Store;
use App\Models\WincodeStore;
use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

/**
 * 处理应答时先判断协议字段返回，
 * <return_code>SUCCESS</status>
 * <return_msg>SYSERR</return_msg>
 * 再判断业务返回，
 * <result_code>FAIL</result_code>
 * 最后判断交易状态
 * <err_code><![CDATA[AUTHCODE_EXPIRE]]></err_code>
 * <err_code_des><![CDATA[二维码已过期，请刷新再试]]></err_code_des>
 *
 * Class IndexController
 * @package App\Api\Controllers\WinCode
 */
class IndexController extends BaseController
{
    /**
     * 收钱啦与服务端交互
     *
     * 1. 收钱啦需要服务端提供APPID和SECRET用来实现身份标识及加密（可参考签名算中的APPID和SECRET的格式及长度）
     * 2. 附加参数“device_id”为款台的唯一标识，用作收钱啦的唯一身份ID
     * device_id通过客户端激活流程获取，说明如下
     * 1.服务端提供款台密钥(激活码)给商户
     * 2.商户将款台密钥(激活码)输入到客户端
     * 3.客户端post请求服务端激活地址(服务端自定义激活地址) 并获取返回device_id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function interaction(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
//            file_put_contents('b3221111.log',var_export($data,true)."\r\n",FILE_APPEND);
            $data = $this->xml_to_array($data);
            Log::channel('pay')->info("interaction" . date("Y-m-d H:i:s", time()), $data);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $method = $data['method'] ?? 'device.register'; //device.register
            $version = $data['version'] ?? '1.0.0'; //1.0.0
            $sign = $data['sign'] ?? ''; //签名
            $nonce_str = $data['nonce_str'] ?? ''; //随机数
            $appid = $data['appid'] ?? ''; //
            $device_token = $data['device_token'] ?? ''; //服务端提供的款台密钥(激活码)
            if (!$device_token) {
                Log::channel('pay')->error("客户端没有收到激活码" . date("Y-m-d H:i:s", time()), $data);
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '客户端没有收到激活码'
                ]);
            }

            $winCodeStoreObj = WincodeStore::where('activation_code', $device_token)->first();
            if (!$winCodeStoreObj) {
                Log::channel('pay')->error("激活码尚未绑定门店" . date("Y-m-d H:i:s", time()), $data);
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '激活码尚未绑定门店'
                ]);
            }

            $re_data = [
                'version' => $version,
                'charset' => $this->postCharset,
                'sign_type' => 'MD5',
                'nonce_str' => $this->nonceStr(),
                'return_code' => 'SUCCESS',
                'device_id' => $winCodeStoreObj->device_id,
                'device_name' => '默认',
                'store_name' => $winCodeStoreObj->store_name,
                'logo' => url('/zhifu/img/touxiang.png'),
                'result_code' => 'SUCCESS'
            ];

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            Log::channel('pay')->error("激活error" . date("Y-m-d H:i:s", time()), $err);
            return $this->return_data($err);
        }
    }


    /**
     * 收钱啦 交易操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function scan_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = $this->xml_to_array($data);
            file_put_contents('b121.log',var_export($data,true)."\r\n",FILE_APPEND);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            if (!isset($data['method']) || empty($data['method'])) {
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '收钱啦-交易方式未知'
                ]);
            }
            $method = $data['method'];
            Log::channel("daily")->info($method);
            switch ($method) {
                case 'trade.micropay': //付款码支付
                    return $this->b_2_c($data);
                    break;
                case 'trade.query': //查询订单
                    return $this->order_query($data);
                    break;
                case 'trade.refund': //退款
                    return $this->refund($data);
                    break;
                case 'trade.refund.query': //退款查询
                    return $this->refund_query($data);
                    break;
            }
        } catch (\Exception $ex) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage() .' | '. $ex->getLine()
            ];
            return $this->return_data($err);
        }
    }



    /**
     * 付款码支付
     *
     * 1. 支付请求后： return_code 和 result_code 字段返回都为SUCCESS时，判定订单支付成功；
     * 2. 支付请求后： return_code 返回为 SUCCESS，而 result_code 返回不为 SUCCESS 时，并且返回的参数 need_query为 N时，才不用调查询接口，其他情况（包括没有返回 need_query参数， 返回了 need_query 参数但值为Y）则必须调用订单查询接口进行确认
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function b_2_c($data)
    {
        try {

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = $data['device_id'] ?? ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //商户系统内部的订单号,32个字符内、可包含字母,确保在同一商户号下唯一
            $total_fee = $data['total_fee'] ?? 0; //总金额，以分为单位，不允许包含任何字、符号
            $body = $data['body'] ?? ''; //商品描述
            $auth_code = $data['auth_code'] ?? ''; //扫码支付授权码， 设备读取用户展示的条码或者二维码信息
            $op_user = $data['op_user'] ?? ''; //否,String(32),操作员账号
            $attach = $data['attach'] ?? ''; //否,String(128),商户附加信息，可做扩展参数
            $spbill_create_ip = $data['spbill_create_ip'] ?? get_client_ip(); //订单生成的机器 IP (使用收钱啦SDK会默认获取，可选填)
            $time_start = $data['time_start'] ?? ''; //否,String(128),订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。时区为GMT+8 beijing。该时间取自商户服务器
            $time_expire = $data['time_expire'] ?? ''; //否,String(14),订单超时时间
            $goods_tag = $data['goods_tag'] ?? ''; //否,String(32),商品标记，微信平台配置的商品标记，用于优惠券或者满减使用
            $detail = $data['detail'] ?? ''; //否,String(6000),单品优惠活动该字段必传，且必须按照规范上传，JSON格式
            $limit_pay = $data['limit_pay'] ?? ''; //否,String(32),no_credit--指定不能使用信用卡支付
            $product_id = $data['product_id'] ?? ''; //否,String(32),预留字段此id为静态可打印的二维码中包含的商品ID，商户自行维护
            $member_mobile = $data['member_mobile'] ?? ''; //否,String(16),会员手机号,与会员卡号任选其一
            $member_card_id = $data['member_card_id'] ?? ''; //否,String(64),会员卡号,与会员手机号任选其一

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            $pay_method = 'qr_code';

            //刷脸处理
            $strlen = strlen($auth_code);
            if ($strlen > 18) {
                $substr = substr($auth_code, -1); //截取判断最后一个
                // $auth_code = substr($auth_code, 0, -1); //去掉最后一个
                $str = substr($auth_code, 0, 2);

                //支付宝刷脸
                if ($substr == '2' && in_array($str, ['28'])) {
                    $pay_method = 'alipay_face';
                }

                //微信刷脸
                if ($substr == '2' && in_array($str, ['13', '14'])) {
                    $pay_method = 'weixin_face';
                }
            }

            //调用系统前参数
            $ro_data = [
                'store_id' => $store_id, //
                'code' => $auth_code,
                'total_amount' => $total_fee / 100,
                'shop_price' => $total_fee / 100,
                'qwx_no' => $out_trade_no, //
                'remark' => '', //
                'device_id' => $device_id, //
                'shop_name' => '商品',
                'shop_desc' => $body ?? '商品',
                'pay_method' => $pay_method
            ];
            if ($merchant_id) $ro_data['merchant_id'] = $merchant_id;
            if ($merchant_name) $ro_data['merchant_name'] = $merchant_name;
            //发起交易
            $order = new TradepayTwoController();
            $tra_data = $order->scan_pay($ro_data);
            Log::channel("daily")->info("scan_pay",[$tra_data]);
            $tra_data_arr = json_decode($tra_data, true);
            Log::channel("gtxy")->info("win_scan_pay",[
                "req"=>$ro_data,
                "res"=>$tra_data
            ]);
            $out_transaction_id = '';
            $time_end = '';
            $re_data = [
                'version' => '1.0.0', //版本号,
                'charset' => 'UTF-8', //字符集
                'sign_type' => 'MD5', //签名类型，取值：MD5
                'appid' => $appid, //String(32),我方支付分配的应用ID
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串，不长于32位
                'return_code' => 'SUCCESS', //SUCCESS/FAIL。此字段是通信标识，非交易标识，交易是否成功需要查看 result_code 来判断
                'device_info' => $device_id,
                'result_code' => 'SUCCESS', //String(16),SUCCESS/FAIL
                'sign' => '', //String(32),MD5签名结果
                'need_query' => 'N', //否,String(32),用来判断是否需要调用查询接口，值为Y或空时需要，值为N时不需要
            ];

            //用户支付成功
            if ($tra_data_arr['status'] == 1) {
                //微信，支付宝支付凭证
                $out_transaction_id = isset($tra_data_arr['data']['out_transaction_id']) ? $tra_data_arr['data']['out_transaction_id'] : "";

                //快钱微信处理
                $mybank_weixin = substr($out_transaction_id, 0, 4);
                if ($mybank_weixin == "MYBK") {
                    $out_transaction_id = strtolower($out_transaction_id); //大写转小写
                }

                $trade_type = '';
                $ways_source = isset($tra_data_arr['data']['ways_source'])? $tra_data_arr['data']['ways_source']:'';
                if ($ways_source) {
                    if ($ways_source == 'alipay') $trade_type = 'pay.alipay.micropay';
                    if ($ways_source == 'weixin') $trade_type = 'pay.weixin.micropay';
                    if ($ways_source == 'unionpay') $trade_type = 'pay.qpass.micropay';
                }

                if (isset($tra_data_arr['data']['pay_time'])) $time_end = date('YMDHis', strtotime($tra_data_arr['data']['pay_time']));

                $re_data['out_transaction_id'] = $out_transaction_id; //String(32),平台交易单号
                $re_data['mch_transaction_id'] = isset($tra_data_arr['data']['trade_no']) ? $tra_data_arr['data']['trade_no']: $out_transaction_id; //String(32),通道订单号，32个字符内、可包含字母
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no']; //String(32),商户系统内部的订单号，32个字符内、可包含字母
                $re_data['total_fee'] = $tra_data_arr['data']['total_amount']*100; //Int,总金额，以分为单位，不允许包含任何字、符号
                $re_data['trade_type'] = $trade_type;
                $re_data['time_end'] = $time_end ?? date('YMDHis', time());
            } //其他错误
            else {
                $data['result_code'] = 'FAIL'; //String(16),SUCCESS/FAIL
                $data['appid'] = $appid; //String(32),我方支付分配的应用ID
                $data['nonce_str'] = $this->nonceStr(); //String(32),随机字符串，不长于32位
                $re_data['result_code'] = 'FALL';
            }

            //处理支付失败订单
            if ($tra_data_arr['pay_status'] == '3' || $tra_data_arr['pay_status'] == 3) {
                if (!empty($tra_data_arr['data']['out_trade_no'])) {
                    $payservice=new PayService();
                    $payservice->closeOrder($tra_data_arr['data']['out_trade_no']);
                }
            }
            //处理支付失败订单

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() .' | '. $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    /**
     * 查询订单
     *
     * 需要调用查询接口的情况：
     * 当商户后台、网络、服务器等出现异常，商户系统最终未接收到支付通知；
     * 调用支付接口后，返回系统错误或未知交易状态情况；
     * 调用关单或撤销接口API之前，需确认支付状态
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_query($data)
    {
        try {
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = isset($data['device_id']) ? $data['device_id']: ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号
            //业务参数
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : ''; //否,String(32),商户订单号
            $mch_transaction_id = isset($data['mch_transaction_id']) ? $data['mch_transaction_id'] : ''; //否,String(32),第三方平台交易号
            $transaction_id = isset($data['transaction_id']) ? $data['transaction_id'] : ''; //否,String(32),平台交易号,out_trade_no和transaction_id至少一个必填，同时存在时transaction_id优先

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;
            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('other_no', '=', $out_trade_no)
                        ->first();
                }
            }
            //如果订单号为空或者不存在
            if (!$order) {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }

            $out_transaction_id = '';
            $time_end = '';
            $trade_no = $order->trade_no;
            $re_data = [
                'version' => '1.0.0',
                'charset' => 'UTF-8',
                'sign_type' => 'MD5',
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
//                'return_msg' => '', //否,String(128),返回信息如非空为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //业务结果,SUCCESS/FAIL
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串
//                'err_code' => '', //否,String(32),错误代码
//                'err_code_des' => '', //否,String(128),错误代码描述
            ];

            $type = $order->ways_type;
            $out_trade_no = $order->out_trade_no;
            $store_obj = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid')
                ->first();
            $config_id = $store_obj->config_id;
            $store_pid = $store_obj->pid;
            //扫呗 交易查询
            if (30080 == $type || 30081 == $type || 30082 == $type) {
                $config = new SaobeiConfigController();
                
                $h_merchant = $config->saobei_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '扫呗商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $wftpay_data = [
                    'pay_ver' => '100',
                    'pay_type' => '000',
                    'service_id' => '020',
                    'merchant_no' => $h_merchant->merchantNo,
                    'terminal_id' => $h_merchant->zhongduan,
                    'terminal_trace' => $out_trade_no,
                    'terminal_time'=>date('YmdHis', time()),
                    'out_trade_no'=>$order->trade_no
                ];
                $return = $obj->order_query3($wftpay_data,$h_merchant->access_token);
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['out_trade_no']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['channel_order_no'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '30080', //返佣来源
                            'source_desc' => '扫呗', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30080) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30081) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30082) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type; 
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //九江银行
            if (37001 == $type || 37002 == $type || 37003 == $type) {
                $config = new JiuJiangConfigController();
                $h_merchant = $config->jiujiang_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '九江银行商户号不存在'
                    ]);
                }

                $txnAmt = substr( strval($order->total_amount * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）
                $postdate = [
                    'requestBranchCode' => '0200410000032', // 请求唯一流水号（固定是：0200000000032）
                    'mchtNo' => $h_merchant->mchtNo, // 平台分配的商户号
                    'termNo' => $h_merchant->termNo, // 平台分配的终端号
                    'secMchtNo' => $h_merchant->mchtNo, // 二级商户号（如无，同商户号）
                    'oriTxnDate' => date('Ymd', time()), // 原交易日期（yyyyMMdd）
                    'txnAmt' => $txnAmt, // 交易金额（分，12 位，不足左补 0）
                    'outOrderNo' => $out_trade_no, // 原商户唯一订单号（主被扫下单时，终端生产的唯一流水号）
                ];
                
                $obj = new \App\Api\Controllers\JiuJiang\PayController();
                $return = $obj->order_query($postdate,$h_merchant->private_key);
                if ($return['pay_status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['payNumber']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['payNumber'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '30080', //返佣来源
                            'source_desc' => '扫呗', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 37001) $trade_type = 'pay.weixin.jspay';
                    if ($type == 37002) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 37003) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type; 
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["pay_status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["pay_status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            
            //官方支付宝查询
            if (999 < $type && $type < 1999) {
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid);
                $config = $isvconfig->AlipayIsvConfig($config_id);

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.query';
                $requests = new AlipayTradeQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"" .
                    "  }");
                $status = $aop->execute($requests, '', $storeInfo->app_auth_token);
                $status = $aop->execute($requests, '', $storeInfo->app_auth_token);
                //支付成功
                if ($status->alipay_trade_query_response->trade_status == "TRADE_SUCCESS") {
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.alipay.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = isset($status->alipay_trade_query_response->send_pay_date) ? date('YmdHis', strtotime($status->alipay_trade_query_response->send_pay_date)) : ''; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $status->alipay_trade_query_response->buyer_user_id,
                            'trade_no' => $status->alipay_trade_query_response->trade_no,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,

                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '1000', //返佣来源
                            'source_desc' => '支付宝', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    return $this->return_data($re_data);
                } //等待付款
                elseif ($status->alipay_trade_query_response->trade_status == "WAIT_BUYER_PAY") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单关闭
                elseif ($status->alipay_trade_query_response->trade_status == 'TRADE_CLOSED') {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $status->alipay_trade_query_response->sub_msg;
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //直付通
            if (16000 < $type && $type < 16999) {
                $config_type = '03';
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.query';
                $requests = new AlipayTradeQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"" .
                    "  }");
                $status = $aop->execute($requests, '', '');
                //支付成功
                if ($status->alipay_trade_query_response->trade_status == "TRADE_SUCCESS") {
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.alipay.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['appid'] = $config->app_id; //String(32),服务商公众号appid
                    $re_data['openid'] = $order->user_id; //String(128),用户在服务商appid下的唯一标识
                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = isset($status->alipay_trade_query_response->send_pay_date) ? date('YmdHis', strtotime($status->alipay_trade_query_response->send_pay_date)) : ''; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $status->alipay_trade_query_response->buyer_user_id,
                            'trade_no' => $status->alipay_trade_query_response->trade_no,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '16000', //返佣来源
                            'source_desc' => '支付宝', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

//                    return $this->return_data($re_data);
                } //等待付款
                elseif ($status->alipay_trade_query_response->trade_status == "WAIT_BUYER_PAY") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单关闭
                elseif ($status->alipay_trade_query_response->trade_status == 'TRADE_CLOSED') {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
                else {
                    //其他情况
                    $message = $status->alipay_trade_query_response->sub_msg;
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //官方微信查询
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;

                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], //XXX: 绝对路径！
                    'key_path' => $options['payment']['key_path'],     //XXX: 绝对路径！
                    'sub_mch_id' => $wx_sub_merchant_id,
                    // 'device_info'     => '013467007045764',
                    // 'sub_app_id'      => ''
                ];
                $payment = Factory::payment($config);
                $query = $payment->order->queryByOutTradeNumber($order->out_trade_no);
                //成功
                if ($query['trade_state'] == 'SUCCESS') {
                    //删除商品
                    if ($weixin_store->wx_shop_id && Schema::hasTable('shops')) {
                        Shop::where('store_id', $store_id)
                            ->where('merchant_id', $order->merchant_id)
                            ->delete();
                    }

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $query['openid'],
                            'trade_no' => $query['transaction_id'],
                            'pay_time' => date('Y-m-d H:i:s', strtotime($query['time_end']))
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '2000', //返佣来源
                            'source_desc' => '微信支付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => date('Y-m-d H:i:s', strtotime($query['time_end'])),
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.weixin.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = $query['time_end']; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

//                    return $this->return_data($re_data);
                }
                elseif ($query['trade_state'] == "USERPAYING") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
                else {
                    //其他情况
                    $message = $query['trade_state_desc'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //京东收银支付
            if (5999 < $type && $type < 6999) {
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $return = $obj->order_query($data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['tradeNo'];
                        $channelNoSeq = isset($return['data']['channelNoSeq']) ? $return['data']['channelNoSeq'] : $trade_no; //条码
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['payFinishTime']));
                        $buyer_pay_amount = $return['data']['piAmount'] / 100;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $channelNoSeq,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '6000', //返佣来源
                            'source_desc' => '京东金融', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.qpass.micropay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //快钱支付
            if (2999 < $type && $type < 3999) {
                //读取配置
                $MyBankobj = new MyBankConfigController();
                $mybank_merchant = $MyBankobj->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $MerchantId = $mybank_merchant->MerchantId;
                $wx_AppId = $mybank_merchant->wx_AppId;

                $MyBankConfig = $MyBankobj->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new TradePayController();
                $return = $obj->mybankOrderQuery($MerchantId, $config_id, $order->out_trade_no);
                if ($return['status'] == 0) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = $return['message'];
                    return $this->return_data($re_data);
                }
                $body = $return['data']['document']['response']['body'];
                $TradeStatus = $body['TradeStatus'];

                //成功
                if ($TradeStatus == 'succ') {
                    $OrderNo = $body['MerchantOrderNo'];
                    $GmtPayment = $body['GmtPayment'];
                    $buyer_id = '';
                    $trade_type = '';

                    if ($type == 3001) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 3002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 3003) {
                        $buyer_id = $body['BuyerUserId'];
                        $trade_type = 'pay.qpass.micropay';
                    }
                    if ($type == 3004) {
                        $buyer_id = $body['SubOpenId'];
                        $trade_type = 'pay.qpass.micropay';
                    }

                    $pay_time = date('Y-m-d H:i:s', strtotime($GmtPayment));
                    $payment_method = strtolower($body['Credit']);

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 1,
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_id' => $buyer_id,
                            'trade_no' => $OrderNo,
                            'pay_time' => $pay_time,
                            'payment_method' => $payment_method,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '3000', //返佣来源
                            'source_desc' => '快钱', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $OrderNo ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($GmtPayment)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                elseif ($TradeStatus == 'paying') {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = '请重新扫码';
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //新大陆收银支付
            if (7999 < $type && $type < 8999) {
                //读取配置
                $config = new NewLandConfigController();
                $new_land_config = $config->new_land_config($config_id);
                if (!$new_land_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '新大陆配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $new_land_merchant = $config->new_land_merchant($store_id, $store_pid);
                if (!$new_land_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $request_data = [
                    'out_trade_no' => $order->out_trade_no,
                    'key' => $new_land_merchant->nl_key,
                    'org_no' => $new_land_config->org_no,
                    'merc_id' => $new_land_merchant->nl_mercId,
                    'trm_no' => $new_land_merchant->trmNo,
                    'op_sys' => '3',
                    'opr_id' => $store_obj->merchant_id,
                    'trm_typ' => 'T'
                ];
                $obj = new PayController();
                $return = $obj->order_query($request_data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['orderNo'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['sysTime']));
                        $buyer_pay_amount = $return['data']['amount'] / 100;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '8000', //返佣来源
                            'source_desc' => '新大陆', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            // 'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 8001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 8002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 8003 || $type == 8004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['amount']; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['sysTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }//订单退款
                elseif ($return["status"] == 4) {
                    $message = '订单已经退款';
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //和融通收银支付
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['md_key'] = $h_config->md_key; //
                $data['mid'] = $h_merchant->h_mid; //
                $data['orgNo'] = $h_config->orgNo; //

                $return = $obj->order_query($data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['transactionId'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['timeEnd']));
                        $buyer_pay_amount = $return['data']['totalFee'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '9000', //返佣来源
                            'source_desc' => '和融通', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 9001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 9002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 9003 || $type == 9004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $return['data']['transactionId'] ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['totalFee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['timeEnd'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //联拓富收银支付
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();
                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['outTransactionId'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['payTime']));
                        $buyer_pay_amount = $return['data']['receiptAmount'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');



                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];

                        $this->update_day_order($insert_data, $out_trade_no);


                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '10000', //返佣来源
                            'source_desc' => '联拓覆', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];


                        PaySuccessAction::action($data);

                    }

                    $trade_type = '';
                    if ($type == 10001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 10002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 10003 || $type == 10004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $return['data']['transactionId'] ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['totalFee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['payTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'NOTPAY'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //随行付支付
            if (12999 < $type && $type < 13999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付配置不存在请检查配置';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付配置不存在请检查配置'
//                    ]);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付商户号不存在';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付商户号不存在'
//                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/pay_notify_url'); //回调地址
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['respData']['sxfUuid'];
                        $buyer_pay_amount = $return['data']['respData']['oriTranAmt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '13000', //返佣来源
                            'source_desc' => '随行付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 13001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 13002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 13003 || $type == 13004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $return['data']['respData']['sxfUuid'] ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['respData']['oriTranAmt']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['respData']['tranTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
//                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
//                    return $this->return_data($re_data);
                }
            }

            //随行付A支付
            if (18999 < $type && $type < 19999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbilla_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付a支付未配置';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付配置不存在请检查配置'
//                    ]);
                }

                $vbill_merchant = $config->vbilla_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付a商户号不存在';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付商户号不存在'
//                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/pay_notify_a_url'); //回调地址
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->order_query($data);
//                Log::info('收钱啦-随行付a-订单查询结果：');
//                Log::info($return["status"]);
                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['respData']['sxfUuid'];
                        $buyer_pay_amount = $return['data']['respData']['oriTranAmt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '19000', //返佣来源
                            'source_desc' => '随行付A', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 19001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 19002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 19003 || $type == 19004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $return['data']['respData']['sxfUuid'] ?? $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['respData']['oriTranAmt']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['respData']['tranTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
//                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
//                    return $this->return_data($re_data);
                }
            }

            //哆啦宝支付
            if (14999 < $type && $type < 15999) {
                $manager = new ManageController();
                $dlbconfig = $manager->pay_config($config_id);
                if (!$dlbconfig) {
                    return json_encode([
                        'status' => 2,
                        'message' => '哆啦宝配置配置不存在请检查配置'
                    ]);
                }

                $dlb_merchant = $manager->dlb_merchant($store_id, $store_pid);
                if (!$dlb_merchant && !empty($dlb_merchant->mch_num) && !empty($dlb_merchant->shop_num)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '哆啦宝配置商户未补充商户编号等信息!'
                    ]);
                }

                $query_data = [
                    'agentNum' => $dlbconfig->agent_num,
                    'customerNum' => $dlb_merchant->mch_num,
                    'shopNum' => $dlb_merchant->shop_num,
                    'requestNum' => $order->out_trade_no,
                    'secretKey' => $dlbconfig->secret_key,
                    'accessKey' => $dlbconfig->access_key,
                ];
                $return = $manager->query_bill($query_data);
                if ($return['status'] == 1) {
                    $query_result = $return['data'];
                    if ($query_result['status'] == "SUCCESS") {
                        try {
                            $pay_time = $query_result['completeTime'];
                            $trade_no = $query_result['orderNum'];
                            $buyer_pay_amount = $query_result['orderAmount'];
                            $buyer_id = isset($query_result['openId']) ? $query_result['openId'] : "";

                            //改变数据库状态
                            if ($order->pay_status != 1) {

                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                    'buyer_id' => $buyer_id,
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);

                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '15000', //返佣来源
                                    'source_desc' => '哆啦宝', //返佣来源说明
                                    'company' => $order->company, //
                                    'fee_amount' => $order->fee_amount, //
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'rate' => $order->rate,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $pay_time,
                                    'device_id' => isset($order->device_id) ? $order->device_id : "",

                                ];


                                PaySuccessAction::action($data);

                            }

                            $trade_type = '';
                            if ($type == 15001) $trade_type = 'pay.alipay.jspay';
                            if ($type == 15002) {
                                $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                            }
                            if ($type == 15003 || $type == 15004) $trade_type = 'pay.qpass.micropay';
                            $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                            //trade_state为success
                            $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                            $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                            $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                            $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                            $re_data['total_fee'] = $query_result['orderAmount']*100; //int,总金额，以分为单位
                            $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                            $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                            $re_data['bank_type'] = ''; //String(16),银行类型
                        } catch (\Exception $e) {
                            $message = '订单查询失败' . $e->getLine() . $e->getMessage();
                            $re_data['result_code'] = 'FALL';
                            $re_data['result_msg'] = $message;
                            $re_data['outTradeNo'] = $order->qwx_no;
                        }
                    }
                    elseif ($query_result['status'] == "INIT") {
                        $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    }
                    elseif ($query_result['status'] == "CANCEL") {
                        $re_data['trade_state'] = 'CLOSED';
                    }
                    elseif ($query_result['status'] == "REFUND") {
                        $message = '订单已经退款';
                        $re_data['trade_state'] = 'REFUND';
                        return $this->return_data($re_data);
                    }
                    elseif ($query_result['status'] == "REFUNDING") {
                        $message = '订单退款中';
                        $re_data['trade_state'] = 'REFUND';
                    }
                    elseif ($query_result['status'] == "FUNDFAIL") {
                        $message = '订单退款失败';
                        $re_data['trade_state'] = 'PAYERROR';
                    }
                    else {
                        $message = '订单退款失败';
                        $re_data['trade_state'] = 'PAYERROR';
                    }
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                }
            }

            //传化收银支付
            if (11999 < $type && $type < 12999) {
                //读取配置
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['channel_no'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['paid_at']));
                        $buyer_pay_amount = $return['data']['total_fee'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '12000', //返佣来源
                            'source_desc' => 'TF', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 12001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 12002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 12003 || $type == 12004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['total_fee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['paid_at'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //工行收银支付
            if (19999 < $type && $type < 20199) {
                $config = new LianfuConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '工行商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $data['apikey'] = $h_merchant->apikey; //商户号
                $data['signkey'] = $h_merchant->signkey; //私钥
                $data['appid'] = $h_merchant->appid; //收单机构APPID
                $data['total_amount'] = $order->total_amount; //收单机构APPID
                $data['out_trade_no'] = $out_trade_no; //
                $return = $obj->order_query($data);
//                Log::info('收钱啦-工行查询');
//                Log::info($return);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = isset($return['data']['order_id'])?$return['data']['order_id']:$out_trade_no;
                        $pay_time = date('Y-m-d H:i:s', time());
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '20200', //返佣来源
                            'source_desc' => 'lianfu', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 20001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 20002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 20003 || $type == 20004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', time()); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                }//订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //海科融通 交易查询
            if (21999 < $type && $type < 22999) {
                //读取配置
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通配置不存在请检查配置'
                    ]);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_data = [
                    'trade_no' => $order->trade_no, //trade_no和out_trade_no和channel_trade_no必传其中一个，三个都传则以trade_no为准，推荐使用trade_no
                    'out_trade_no' => $order->out_trade_no, //服务商的交易订单编号
                    'channel_trade_no' => '', //凭证条码订单号
                    'access_id' => $hkrt_config->access_id,
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('海科融通-收钱啦-交易查询-入参');
//                Log::info($hkrt_data);
                $return = $obj->order_query($hkrt_data); //0-系统错误 1-交易成功；2-交易失败；3-交易进行中；4-交易超时
//                Log::info('海科融通-收钱啦-交易查询-结果');
//                Log::info($return);

                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = $return['data']['trade_end_time'];
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['trade_no'];
                        $buyer_pay_amount = $return['data']['total_amount'];


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '22000', //返佣来源
                            'source_desc' => '海科融通', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 22001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 22002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 22003 || $type == 22004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['total_amount']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //交易进行中
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }//交易超时
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //易生支付 交易查询
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }

                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付配置不存在请检查配置'
                    ]);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\EasyPay\PayController();
                $easypay_data = [
                    'channel_id' => $easypay_config->channel_id, //渠道编号
                    'mer_id' => $easypay_merchant->termMercode, //终端商户编号
                    'device_id' => $easypay_merchant->termTermcode, //终端编号
                    'out_trade_no' => $order->out_trade_no, //原交易流水
                    "private_key"=>$easypay_config->private_key
                ];
//                Log::info('易生支付-收钱啦-交易查询-入参');
//                Log::info($easypay_data);
                $return = $obj->order_query($easypay_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//                Log::info('易生支付-收钱啦-交易查询-结果');
//                Log::info($return);

                $pay_time = isset($return['data']['wxtimeend']) ? date('Y-m-d H:i:s', strtotime($return['data']['wxtimeend'])): ''; //支付完成时间，格式为 yyyyMMddhhmmss
                $trade_no = $return['data']['wtorderid'] ?? ''; //系统订单号
                $buyer_pay_amount = isset($return['data']['payamt']) ? ($return['data']['payamt'] / 100): ''; //实付金额，单位分
                $buyer_id = $return['data']['wxopenid'] ?? ''; //用户在商户 appid 下的唯一标识(微信/支付宝渠道返回)

                //支付成功
                if ($return['status'] == '1') {
                    //改变数据库状态
                    if ($order->pay_status != '1') {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => '1',
                            'pay_status_desc' => '支付成功',
                            'buyer_id' => $buyer_id,
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '21000', //返佣来源
                            'source_desc' => '易生支付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 21001 || $type == 61001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 21002 || $type == 61002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 21003 || $type == 21004 || $type == 61003 || $type == 61004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = isset($return['data']['payamt']) ? $return['data']['payamt']: $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['wxtimeend'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //交易进行中
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
                //交易超时
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            // 国通支付 交易查询  gtxy
            if(in_array($type,[62001,62002,62004,62011,62012,62014])){
                Log::channel("gtxy")->info("wincode—query-1",[
                    "type"=>$type,
                    "order"=>$order
                ]);
                $store = Store::query()->where(["store_id"=>$store_id])->first();
                $result=BizService::gtxy_query($order,$store,"",$this);
                $return=json_decode($result,true);
                Log::channel("gtxy")->info("wincode—query-2",[
                    "return"=>$return,
                ]);
//                'ways_source' => $order->ways_source,
//                    'pay_time' => $pay_time,
//                    'out_trade_no' => $order->out_trade_no,
//                    'pay_amount' => $payamt,
//                    'total_amount' => $order->total_amount,
//                    'other_no' => $other_no,
//                    'trade_no' => $trade_no
                if ($return['pay_status'] == 1) {
                    $trade_type = '';
                    if ($order->ways_source == 'weixin') $trade_type = 'pay.weixin.jspay';
                    if ($order->ways_source == 'alipay') {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    $buyer_pay_amount = $order->total_amount;
                    if (isset($return['data']['pay_amount'])) {
                        $buyer_pay_amount = $return['data']['pay_amount'];
                    }
                    $pay_time = date('YmdHis');
                    if (isset($return['data']['pay_time'])) {
                        $pay_time = $return['data']['pay_time'];
                    }

                    if ($order->ways_source == 'unionpay') {
                        $trade_type = 'pay.unionpay.jspay';
                    }
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type;
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $return['data']['trade_no']??"";; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100;//$buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = $pay_time; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                elseif($return['pay_status'] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            //邮储 交易查询
            if (26000 < $type && $type < 26999) {
                $config = new LianfuyoupayConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfuyouzheng\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['pos_sn'] = $h_merchant->pos_sn;
                $data['goods_name'] = '商品'; //

                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = isset($return['data']['orderNo'])?$return['data']['orderNo']:$out_trade_no;
                        $pay_time = date('Y-m-d H:i:s', time());
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '26000', //返佣来源
                            'source_desc' => 'lianfuyoupay', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['result_msg'] = '支付成功';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    $re_data['out_transaction_id'] = $trade_no; //$query['transaction_id'];
                    $re_data['time_end'] = date('YmdHis', time());

                    $trade_type = '';
                    if ($type == 26001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 26002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 26003 || $type == 26004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', time()); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //葫芦天下
            if (22999 < $type && $type < 23999) {
                $manager = new \App\Api\Controllers\Hltx\ManageController();
                $hltx_merchant = $manager->pay_merchant($store_id, $store_pid);
                $qd = $hltx_merchant->qd;

                $hltx_config = $manager->pay_config($config_id, $qd);
                if (!$hltx_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => 'HL支付配置不存在请检查配置'
                    ]);
                }

                $manager->init($hltx_config);

                switch ($type) {
                    case 23001:
                        $pay_channel = 'ALI';
                        break;
                    case 23002:
                        $pay_channel = 'WX';
                        break;
                    case 23004:
                        $pay_channel = 'UPAY';
                        break;
                    default:
                        $pay_channel = 'ALI';
                        break;
                }

                if (!$hltx_merchant || empty($hltx_merchant->mer_no)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户未成功开通HL通道!'
                    ]);
                }

                $hltx_data = [
                    'merNo' => $hltx_merchant->mer_no,
                    'orderNo' => $order->out_trade_no
                ];
                $return = $manager->query_order($hltx_data);
                if ($return['status'] == 1) {
                    $return = $return['data'];
                    if ($return['tradeStatus'] == "S") {
                        if ($return['subTradeStatus'] == 'COMPLETE') {
                            try {
                                $pay_time = $return['payCompleteTime'];
                                $trade_no = $return['transIndex'];
                                $buyer_pay_amount = $return['amount'] / 100;
                                //改变数据库状态
                                if ($order->pay_status != 1) {

                                    $insert_data = [
                                        'status' => '1',
                                        'pay_status' => 1,
                                        'pay_status_desc' => '支付成功',
                                        'buyer_logon_id' => '',
                                        'trade_no' => $trade_no,
                                        'pay_time' => $pay_time,
                                        'buyer_pay_amount' => $buyer_pay_amount,
                                    ];
                                    $this->update_day_order($insert_data, $out_trade_no);

                                    //支付成功后的动作
                                    $data = [
                                        'ways_type' => $order->ways_type,
                                        'ways_type_desc' => $order->ways_type_desc,
                                        'source_type' => '23000', //返佣来源
                                        'source_desc' => 'HL', //返佣来源说明
                                        'company' => 'hltx', //返佣来源说明
                                        'total_amount' => $order->total_amount,
                                        'out_trade_no' => $order->out_trade_no,
                                        'rate' => $order->rate,
                                        'merchant_id' => $order->merchant_id,
                                        'store_id' => $order->store_id,
                                        'user_id' => $order->user_id,
                                        'config_id' => $config_id,
                                        'store_name' => $order->store_name,
                                        'ways_source' => $order->ways_source,
                                        'pay_time' => $pay_time,
                                        'device_id' => isset($order->device_id) ? $order->device_id : "",
                                    ];
                                    PaySuccessAction::action($data);
                                }

                                $trade_type = '';
                                if ($type == 23001) $trade_type = 'pay.alipay.jspay';
                                if ($type == 23002) {
                                    $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                                }
                                if ($type == 23003 || $type == 23004) $trade_type = 'pay.qpass.micropay';
                                $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                                //trade_state为success
                                $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                                $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                                $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                                $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                                $re_data['total_fee'] = $return['amount']; //int,总金额，以分为单位
                                $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                                $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                                $re_data['bank_type'] = ''; //String(16),银行类型
                            } catch (\Exception $e) {
                                $message = '订单查询失败' . $e->getLine() . $e->getMessage();
                                $re_data['result_code'] = 'FALL';
                                $re_data['result_msg'] = $message;
                                $re_data['outTradeNo'] = $order->qwx_no;
                            }
                        } //订单支付失败
                        elseif (in_array($return['subTradeStatus'], ['FAILED', 'SYS_FAILED', 'CANCEL', 'CLOSE'])) {
                            $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                        } //等待用户付款
                        else {
                            $re_data['trade_state'] = 'USERPAYING';
                        }
                    } //订单支付失败
                    elseif ($return['tradeStatus'] == "E") {
                        $re_data['trade_state'] = 'PAYERROR';
                    } //等待用户付款
                    else {
                        $re_data['trade_state'] = 'USERPAYING';
                    }
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                }
            }

            //联动优势 交易查询
            if (4999 < $type && $type < 5999) {
                $obj = new LinkagePayController();
                $linkage_data = [
                    'out_trade_no' => $out_trade_no //商户订单号
                ];
                $return = $obj->order_query($linkage_data);

                if ($return['pay_status'] == '1') { //支付成功
                    $pay_time = date('Y-m-d H:i:s', time()); //交易时间 格式：MMDDhhmmss
                    $trade_no = $return['data']['trade_no']; //联动优势的流水号
                    $buyer_pay_amount = isset($return['data']['txnAmt']) ? ($return['data']['txnAmt']/100): $order->total_amount; //订单金额 (打印小票使用)
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $paySeq = '';
                    $depBankSeq = $return['data']['depBankSeq'] ?? ''; //第三方流水号（微信/支付宝/银联的交易流水号）

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'auth_code' => $paySeq,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '5000', //返佣来源
                            'source_desc' => '联动优势', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 5001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 5002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 5003 || $type == 5004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //交易失败
                elseif ($return["pay_status"] == '2') {
                    $re_data['trade_state'] = 'USERPAYING';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //威富通 交易查询
            if (26999 < $type && $type < 27999) {
                $config = new WftPayConfigController();
                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付配置不存在请检查配置'
                    ]);
                }

                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通商户号不存在'
                    ]);
                }

                $obj = new WftPayPayController();
                $wftpay_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通-收钱啦-交易查询-入参');
//                Log::info($wftpay_data);
                $return = $obj->order_query($wftpay_data); //0-系统错误 1-成功 2-失败 3-转入退款 4-未支付 5-已关闭 6-已冲正 7-已撤销 8-用户支付中
//                Log::info('威富通-收钱啦-交易查询');
//                Log::info($return);

                if ($return['status'] == 1) {
                    $pay_time = $return['data']['time_end'] ? date('Y-m-d H:i:s', strtotime($return['data']['time_end'])): ''; //支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010
                    $trade_no = $return['data']['transaction_id']; //平台交易号
                    $buyer_pay_amount = $return['data']['total_fee'] ? ($return['data']['total_fee']/100): $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '27000', //返佣来源
                            'source_desc' => '威富通', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 27001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 27002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 27003 || $type == 27004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //用户支付中
                elseif ($return["status"] == 8) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
                //未支付
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'NOTPAY';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //银联商务 交易查询
//            if (30020 == $type || 30021 == $type || 30022 == $type) {
            if(in_array($type,[30020,30021,30022,30023,30024,30025])){

                $config = new MerchConfigController();
                
                $h_merchant = $config->merch_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '银联商务商户号不存在'
                    ]);
                }

                $obj = new WftPayPayController();
                $wftpay_data = [
                    'merchantCode' => $h_merchant->MerchantId,
                    'merchantOrderId' => $out_trade_no,
                    'terminalCode' => $h_merchant->merchzhongduanid,
                ];
                $Authorization=$h_merchant->accessToken;
                if(in_array($type,[30020,30021,30022])){
                    $return = $obj->order_query1($Authorization,$wftpay_data);
                }elseif(in_array($type,[30023,30024,30025])){

                    $wftpay_data["appId"] = $h_merchant->merch_appid;
                    $wftpay_data["appKey"] = $h_merchant->merch_appkey;
                    $wftpay_data["store_id"] = $store_id;
                    $return = $obj->order_queryV6($wftpay_data);
                }
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['out_transaction_id']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '27000', //返佣来源
                            'source_desc' => '威富通', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30020) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30021) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30022) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS'; 
                    $re_data['trade_type'] = $trade_type;
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型\
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //翼支付 交易查询
            if (30050 == $type || 30051 == $type || 30052 == $type || 30053 == $type) {
                $config = new WingConfigController();
                
                $h_merchant = $config->wing_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '翼支付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $wftpay_data = [
                    'institutionCode' => $h_merchant->institutionCode,
                    'outTradeNo' => $out_trade_no,
                    'merchantNo' => $h_merchant->merchantNo,
                    'tradeDate'=>date('Y-m-d H:i:s', time())
                ];
                $return = $obj->order_query1($wftpay_data);
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['tradeNo']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['tradeNo'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '27000', //返佣来源
                            'source_desc' => '威富通', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30050) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30051) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30052) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型\
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //通联支付 交易查询
            if (32000 == $type || 32001 == $type || 32002 == $type) {
                $config = new AllinpayConfigController();

                $h_merchant = $config->allinpay_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '通联支付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                if($h_merchant->orgid){
                    $wftpay_data['orgid'] = $h_merchant->orgid;//机构号
                }
                $wftpay_data = [
                    'cusid' => $h_merchant->cusid,
                    'appid' => $h_merchant->appid,
                    'version' => '11',
                    'reqsn' => $out_trade_no,
                    'randomstr' => time(),
                    'signtype' => 'RSA',
                ];
                $return = $obj->allin_search($wftpay_data,$h_merchant->prikey);
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['trxid']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['trxid'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '32000', //返佣来源
                            'source_desc' => '通联支付', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 32000) $trade_type = 'pay.weixin.jspay';
                    if ($type == 32001) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 32002) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type;
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //酷点 交易查询
            if (30090 == $type || 30091 == $type || 30092 == $type) {
                $config = new CoolConfigController();
                
                $h_merchant = $config->cool_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '酷点商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $karray=array(
                    'mch_id'=>$h_merchant->merchantNo,
                    'timestamp'=>time(),
                    'nonce_str'=>md5(mt_rand(1000, 9999).time()),
                    'sign_type'=>'MD5',
                    'content'=>json_encode(array('out_trade_no'=>$out_trade_no))
                );
                foreach (array_filter($karray) as $k => $v)
                {
                    $Parameters[$k] = $v;
                }
                $buff = "";
                ksort($Parameters);
                foreach ($Parameters as $k => $v) {
                    $buff .= $k . "=" . $v . "&";
                }
                $String = '';
                if (strlen($buff) > 0) {
                    $String = substr($buff, 0, strlen($buff) - 1);
                }
                $String = $String . "&secret_key=" . $h_merchant->secret_key;
                $String = strtoupper(md5($String));
                $karray['sign'] = $String;
                $return = $obj->order_query4($karray);
                
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['pay_no']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['pay_no'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '30090', //返佣来源
                            'source_desc' => '酷点', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30090) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30091) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30092) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type; 
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //平安银行 交易查询
            if (30011 == $type || 30012 == $type || 30013 == $type) {
                $config = new PinganConfigController();
                
                $h_merchant = $config->pingan_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '平安银行商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $pingan_data['out_order_id']=$out_trade_no;
                $pingan_data['enterpriseReg']=$h_merchant->enterpriseReg;
                $pingan_data['merchant_id']=$h_merchant->merchant_id;
                
                foreach (array_filter($pingan_data) as $k => $v){
                    $Parameters[$k] = $v;
                }
                $buff = "";
                ksort($Parameters);
                foreach ($Parameters as $k => $v) {
                    $buff .= $k . "=" . $v . "&";
                }
                $String = '';
                if (strlen($buff) > 0) {
                    $String = substr($buff, 0, strlen($buff) - 1);
                }
                $String = $String . $h_merchant->appsecret;
                $re=hash('sha256', $String, true);
                $String = strtoupper(bin2hex($re));
                
                $json='{"appid":"'."$h_merchant->appid".'"'.',"timeStamp":"'.time().'000'.'"'.',"data":'.stripslashes(json_encode($pingan_data,JSON_UNESCAPED_SLASHES)).',"sign":"'.$String.'"'.'}';
                $return = $obj->order_query6($json);
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['third_order_id']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['leshua_order_id'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '30090', //返佣来源
                            'source_desc' => '酷点', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30011) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30012) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30013) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type; 
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
            //农行bmp 交易查询
            if (30001 == $type || 30002 == $type || 30003 == $type) {
                $config = new AbcConfigController();
                
                $h_merchant = $config->abc_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '农行商户号不存在'
                    ]);
                }
                $obj = new WftpayPayController();
                $data1['trans_type'] = '02';//交易类型
                $data1['mer_id'] = $h_merchant->MerchantId;//key
                $data1['term_id'] = $h_merchant->abczhongduanid;//终端号
                $data1['out_trade_no'] = $out_trade_no;
                $data1['total_amount'] = $order->total_amount;
                $data1['app_id'] = $h_merchant->abckey;//商户号
                $data1['private_rsa_key'] = $h_merchant->private_rsa_key;
                $data1['public_rsa_key'] = $h_merchant->public_rsa_key;
                $return = $obj->order_query2($data1);
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['order_id']; //平台交易号
                    $buyer_pay_amount = $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['order_id'] ?? ''; //第三方交易号
                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '30001', //返佣来源
                            'source_desc' => '农行bmp', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 30001) $trade_type = 'pay.weixin.jspay';
                    if ($type == 30002) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 30003) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type; 
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                //用户支付中
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //汇旺财 交易查询
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付配置不存在请检查配置'
                    ]);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财商户号不存在'
                    ]);
                }

                $obj = new HwcPayPayController();
                $hwcpay_data = [
                    'mch_id' => $hwcpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财-收钱啦-交易查询-入参');
//                Log::info($hwcpay_data);
                $return = $obj->order_query($hwcpay_data); //0-系统错误 1-成功 2-失败 3-转入退款 4-未支付 5-已关闭 6-已冲正 7-已撤销 8-用户支付中
//                Log::info('汇旺财-收钱啦-交易查询');
//                Log::info($return);

                if ($return['status'] == 1) {
                    $pay_time = $return['data']['time_end'] ? date('Y-m-d H:i:s', strtotime($return['data']['time_end'])): ''; //支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010
                    $trade_no = isset($return['data']['third_order_no']) ? $return['data']['third_order_no'] : $return['data']['transaction_id']; //平台交易号
                    $buyer_pay_amount = $return['data']['total_fee'] ? ($return['data']['total_fee']/100): ''; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '28000', //返佣来源
                            'source_desc' => '汇旺财', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 28001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 28002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 28003 || $type == 28004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //用户支付中
                elseif ($return["status"] == 8) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //订单支付失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //未支付
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'NOTPAY';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }
            
             //农商行 交易查询
            if (20800 < $type && $type < 20899) {
                $config = new \App\Api\Controllers\Config\NongjinConfigController();
                $h_merchant = $config->nongjin_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '农商行商户号不存在'
                    ]);
                }
                //发起查询
                $obj = new \App\Api\Controllers\lianfu\PayController();
                $wftpay_data = [
                    'merchantNo' => $h_merchant->merchantNo,
                    'terminalNo' => $h_merchant->terminalNo,
                    'batchNo' => $h_merchant->batchNo,
                    'traceNo' => $h_merchant->batchNo,
                    'outTradeNo' => $out_trade_no,
                    'signkey' => $h_merchant->signkey,
                    'nonceStr'=>time()
                ];
                $return = $obj->order_query2($wftpay_data);
                //支付成功
                if ($return['status'] == 1) {
                    $pay_time = date('Y-m-d H:i:s', time());
                    $trade_no = $return['data']['chnOrderId'];
                    $buyer_pay_amount = $order->total_amount;
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['chnOrderId'];

                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '20801', //返佣来源
                            'source_desc' => '农商行', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }
                    $trade_type = '';
                    if ($type == 20801) $trade_type = 'pay.weixin.jspay';
                    if ($type == 20802) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 20803) $trade_type = 'pay.unionpay.jspay';
                    $re_data['trade_state'] = 'SUCCESS';
                    $re_data['trade_type'] = $trade_type;
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                    return $this->return_data($re_data);
                }
                elseif($return['status'] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //聚合支付logic-查询
            $company = ucfirst($order->company);
            if (method_exists("App\Api\Controllers\\$company\LogicController",'queryParams')) {
                try {
                    $class = "\\App\\Api\\Controllers\\$company\\LogicController";
                    $return = json_decode((new $class)->queryParams($store_id, $store_pid, $data, $order), true);
                    //支付成功
                    if ($return['pay_status'] == 1) {

                        $trade_type = '';
                        if ($order->ways_source == 'weixin') $trade_type = 'pay.weixin.jspay';
                        if ($order->ways_source == 'alipay') {
                            $trade_type = 'pay.alipay.jspay';
                        }
                        $buyer_pay_amount = $order->total_amount;
                        if (isset($return['data']['pay_amount'])) {
                            $buyer_pay_amount = $return['data']['pay_amount'];
                        }
                        $pay_time = date('YmdHis');
                        if (isset($return['data']['pay_time'])) {
                            $pay_time = $return['data']['pay_time'];
                        }

                        if ($order->ways_source == 'unionpay') $trade_type = 'pay.unionpay.jspay';
                        $re_data['trade_state'] = 'SUCCESS';
                        $re_data['trade_type'] = $trade_type;
                        $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                        $re_data['out_transaction_id'] = $return['data']['trade_no'];; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['total_fee'] = $buyer_pay_amount*100;//$buyer_pay_amount*100; //int,总金额，以分为单位
                        $re_data['time_end'] = $pay_time; //String(128),订单支付时间
                        $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                        $re_data['bank_type'] = ''; //String(16),银行类型
                        return $this->return_data($re_data);
                    }
                    elseif($return['pay_status'] == 2) {
                        $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                        return $this->return_data($re_data);
                    }
                    else {
                        $re_data['trade_state'] = 'PAYERROR';
                        return $this->return_data($re_data);
                    }

                } catch (\Exception $exception) {
                    $re_data['trade_state'] = 'USERPAYING';
                    error_log(date('Y-m-d H:i:s')." 【mergePay】： ".json_encode([$exception->getMessage()])."\n\n", 3, "/tmp/". 'mergePay'.date('Ymd').".log");

                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage(). '|' .$exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    /**
     * 退款
     *
     * 同一笔单的部分退款需要设置相同的订单号和不同的 out_refund_no 。总退款金额不能超过用户实际支付金额(现金券金额不能退款)
     *
     * 商户在退款操作时应该注意退款限制，避免发起不会成功的退款请求，下面是主要的退款限制：
     * 1. 在退款累计金额不超过交易订单支付总额情况下，一笔交易单可以多次退款。退款申请单号由商户生成，所以商户一定要保证退款申请单的唯一性。
     * 2. 目前大多数银行都支持全额退款和部分退款，但是也有少数银行不支持全额退款或部分退款，或者不支持退款。在这种情况下，商户可以与买家协调，线下直接退给买家。
     * 3. 当天同一门店下某支付通道总退款金额不能超出该门店下该支付通道总收入金额，例：门店今日支付宝通道收入金额为0，无法完成退款操作
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function refund($data)
    {
        try {
            
            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = isset($data['device_id']) ? $data['device_id']: ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //否,String(32),商户订单号
            $transaction_id = $data['transaction_id'] ?? ''; //否,String(32),平台订单号,out_trade_no和transaction_id至少一个必填，同时存在时transaction_id优先
            $out_refund_no = $data['out_refund_no'] ?? ''; //String(32),商户退款单号,32个字符内、可包含字母,确保在商户系统唯一
            $total_fee = $data['total_fee'] ?? ''; //int,订单总金额，单位为分
            $refund_fee = $data['refund_fee'] ?? ''; //int,退款总金额,单位为分,可以做部分退款
            $op_user_id = $data['op_user_id'] ?? ''; //String(32),操作员帐号,默认为商户号

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->select('id', 'ways_source', 'company', 'ways_type','created_at', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount',"config_id","other_no")
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type','created_at', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount',"config_id","other_no")
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type','created_at', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount',"config_id","other_no")
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('other_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'created_at','ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount',"config_id","other_no")
                        ->first();
                }
            }

            //如果订单号为空或者不存在
            if (!$order) {
                Log::info('收钱啦-查询订单-无果：');
                Log::info($out_trade_no);
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }
            else {
                //判断有没有退款全部完成
                if ($order->refund_amount == $order->total_amount) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '此订单号已经全部退款';
                    return $this->return_data($re_data);
                }
            }

            $OutRefundNo = $out_refund_no; //
            $out_transaction_id = $order->trade_no;
            $out_trade_no = $order->out_trade_no;
            $refundFee_fen = $refund_fee; //退款金额单位 /分

            $already_refund_amount = ($order->refund_amount * 100); //已退款金额,分
            if (($refundFee_fen + $already_refund_amount) > ($order->total_amount * 100)) {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '退款金额大于总金额';
                return $this->return_data($re_data);
            }

            $refundFee_yuan = number_format($refundFee_fen / 100, 2, '.', '');
            $refund_amount = $refundFee_yuan;

            $total_amount = $order->total_amount; //交易总额
            $rate = $order->rate; //订单但是费率
            $new_refund_amount = $order->refund_amount + $refund_amount; //总退款
            $new_fee_amount = ($total_amount - $new_refund_amount) * ($rate/100); //退款后的手续费

            //暂时只支持退全款
//            if ($refundFee_yuan != $order->total_amount) {
//                $re_data['result_code'] = 'FALL';
//                $re_data['result_msg'] = '只支持退全额';
//                return $this->return_data($re_data);
//            }
            $time_end = '';
            $re_data = [
                'version' => '1.0.0',
                'charset' => 'UTF-8',
                'sign_type' => 'MD5',
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
                'return_msg' => '', //否,String(128),返回信息如非空为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //业务结果,SUCCESS/FAIL
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串
                'err_code' => '', //否,String(32),错误代码
                'err_code_des' => '', //否,String(128),错误代码描述
            ];

            $type = $order->ways_type;
            $store_obj = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid')
                ->first();
            $config_id = $store_obj->config_id;
            $store_pid = $store_obj->pid;
            
            if( $order->created_at < date('Y-m-d 00:00:00', time()) ){
                 if($store_id != '20231191759057240'){
                    $re_data = [
                        'status' => 2,
                        'message' => '退款失败, 超过退款时效',
                    ];
                    return json_encode($re_data);
                }
            }
            //支付宝官方
            if (999 < $type && $type < 1999) {
                $isvconfig = new AlipayIsvConfigController();
                $config_type = '01';
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid); //获取token

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = "alipay.trade.refund";

                $requests = new AlipayTradeRefundRequest();
                $data_req_ali = "{" .
                    "\"out_trade_no\":\"" . $order->out_trade_no . "\"," .
                    "\"refund_amount\":\"" . $refund_amount . "\"," .
                    "\"out_request_no\":\"" . $OutRefundNo . "\"," .
                    "\"refund_reason\":\"正常退款\"" .
                    "}";
                $requests->setBizContent($data_req_ali);
                $result = $aop->execute($requests, null, $storeInfo->app_auth_token);
                $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;

                //退款成功
                if (!empty($resultCode) && $resultCode == 10000) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $result->$responseNode->sub_msg;
                }
            }

            //直付通
            if (16000 < $type && $type < 16999) {
                $config_type = '03';
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = "alipay.trade.refund";

                $requests = new AlipayTradeRefundRequest();
                $data_re = array(
                    'out_trade_no' => $out_trade_no,
                    'refund_amount' => $refund_amount,
                    'out_request_no' => $OutRefundNo,
                    'refund_reason' => '正常退款'
                );

                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'settle_orders_' . $day;
                if (Schema::hasTable($table)) {
                    $settle_orders = DB::table($table)->where('out_trade_no', $out_trade_no)
                        ->where('store_id', $store_id)
                        ->first();
                    if ($settle_orders && $settle_orders->order_settle_amount > 0) {
                        $data_re['refund_royalty_parameters'] = array(
                            0 => array(
                                'trans_out' => $settle_orders->trans_out,
                                'amount' => $settle_orders->order_settle_amount,
                                'desc' => '退款分账'
                            )
                        );
                    }
                }

                $data_re = json_encode($data_re);
                $requests->setBizContent($data_re);
                $result = $aop->execute($requests, null, '');
                $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;

                //退款成功
                if (!empty($resultCode) && $resultCode == 10000) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $result->$responseNode->sub_msg;
                }
            }

            //微信官方扫码退款
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;

                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], // XXX: 绝对路径！！！！
                    'key_path' => $options['payment']['key_path'],     // XXX: 绝对路径！！！！
                    'sub_mch_id' => $wx_sub_merchant_id
                ];

                $payment = Factory::payment($config);
                // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
                $refund = $payment->refund->byOutTradeNumber($order->out_trade_no, $OutRefundNo, $order->total_amount * 100, $refund_amount * 100);
                //Log::info('收钱啦-微信官方扫码退款');
                //Log::info($refund);
                if ($refund['return_code'] == "SUCCESS") {
                    //退款成功
                    if ($refund['result_code'] == "SUCCESS") {
                        $insert_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => 6,
                            'status' => 6,
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $OutRefundNo, //退款单号
                            'store_id' => $store_id,
                            'merchant_id' => (int)$merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                        $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } else {
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $refund['result_msg'];
                    }
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $refund['return_msg'];
                }
            }

            //京东收银支付退款
            if (5999 < $type && $type < 6999) {
                //读取配置
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] =$refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联拓富收银支付退款
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();
                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] = $refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $out_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //其他情况
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //快钱收银支付退款
            if (2999 < $type && $type < 3999) {
                //读取配置
                $config = new MyBankConfigController();
                $mybank_merchant = $config->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $wx_AppId = $mybank_merchant->wx_AppId;
                $MyBankConfig = $config->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new TradePayController();
                $MerchantId = $mybank_merchant->MerchantId;
                $RefundAmount =$refund_amount;
                $return = $obj->mybankrefund($MerchantId, $order->out_trade_no, $OutRefundNo, $RefundAmount, $config_id);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //其他情况
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //和融通收银支付退款
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['trade_no'] = $order->trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['mid'] = $h_merchant->h_mid;
                $data['md_key'] = $h_config->md_key; //
                $data['orgNo'] = $h_merchant->orgNo; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] = $refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付支付退款
            if (12999 < $type && $type < 13999) {
                //读取配置
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付配置不存在请检查配置'
                    ]);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $data['refund_amount'] = $refund_amount;
//                Log::info('随行付-收钱啦-退款-入参');
//                Log::info($data);
                $return = $obj->refund($data);
//                Log::info('随行付-收钱啦-退款');
//                Log::info($return);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' =>$refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                }
                elseif(($return['status'] == 0) && ($return['data']['code'] == '0000')){
                    //TODO: 退款状态未知，先让收钱啦显示成功
//                    Log::info('随行付退款状态未知，先让收钱啦显示成功');
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败 其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付a支付退款
            if (18999 < $type && $type < 19999) {
                //读取配置
                $config = new VbillConfigController();
                $vbill_config = $config->vbilla_config($config_id);
                if (!$vbill_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付A配置不存在请检查配置'
                    ]);
                }

                $vbill_merchant = $config->vbilla_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付A商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $data['refund_amount'] = $refund_amount;
//                Log::info('随行付A-收钱啦-退款-入参');
//                Log::info($data);
                $return = $obj->refund($data);
//                Log::info('随行付A-收钱啦-退款');
//                Log::info($return);

                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' =>$refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                }
                elseif(($return['status'] == 0) && ($return['data']['code'] == '0000')){
                    //TODO: 退款状态未知，先让收钱啦显示成功
//                    Log::info('随行付A退款状态未知，先让收钱啦显示成功');
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //传化收银支付退款
            if (11999 < $type && $type < 12999) {
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $OutRefundNo = time();
                $data = [];
                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $data['refund_trade_no'] = $OutRefundNo; //
                $data['refund_fee'] = $refund_amount; //
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //新大陆
            if (7999 < $type && $type < 8999) {
                $config = new NewLandConfigController();
                $new_land_config = $config->new_land_config($config_id);
                if (!$new_land_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '新大陆通道配置不存在';
                    return $this->return_data($re_data);
                }

                $new_land_merchant = $config->new_land_merchant($store_id, $store_pid);
                if (!$new_land_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户新大陆通道未开通';
                    return $this->return_data($re_data);
                }
                $request_data = [
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $order->trade_no,
                    'key' => $new_land_merchant->nl_key,
                    'org_no' => $new_land_config->org_no,
                    'merc_id' => $new_land_merchant->nl_mercId,
                    'trm_no' => $new_land_merchant->trmNo,
                    'op_sys' => '3',
                    'opr_id' => $store_obj->merchant_id,
                    'trm_typ' => 'T',
                    'txnAmt'=>$refund_amount*100,
                ];
                $obj = new PayController();
                $return = $obj->refund($request_data);

                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //哆啦宝
            if (14999 < $type && $type < 15999) {
                $OutRefundNo = "dlbscan" . date('YmdHis') . str_pad(rand(0, 9999), 4, 0);
                $manager = new ManageController();
                $dlb_config = $manager->pay_config($config_id);
                if (!$dlb_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '哆啦宝配置配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $dlb_merchant = $manager->dlb_merchant($store_id, $store_pid);
                if (!$dlb_merchant && !empty($dlb_merchant->mch_num) && !empty($dlb_merchant->shop_num)) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '哆啦宝配置商户未补充商户编号等信息';
                    return $this->return_data($re_data);
                }

                $refund_data = [
                    "accessKey" => $dlb_config->access_key,
                    "secretKey" => $dlb_config->secret_key,
                    "agentNum" => $dlb_config->agent_num,
                    "customerNum" => $dlb_merchant->mch_num,
                    "shopNum" => $dlb_merchant->shop_num,
                    "requestNum" => $out_trade_no,
                    "refundRequestNum" => $OutRefundNo,
                    'refundPartAmount'=>$refund_amount
                ];
                $return = $manager->pay_refund($refund_data);
                if ($return['status'] == 1) {
                    //退款请求成功
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //汇付-收银通道 退款
            if (17999 < $type && $type < 18999) {
                $config = new HuiPayConfigController();
                $hui_pay_config = $config->hui_pay_config($config_id);
                if (!$hui_pay_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '汇付配置不存在请检查配置'
                    ]);
                }

                $hui_pay_merchant = $config->hui_pay_merchant($store_id, $store_pid);
                if (!$hui_pay_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '汇付商户不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\HuiPay\PayController();
                $data['notify_url'] = url('/api/huipay/return_pay_notify_url'); //回调地址
                $data['request_url'] = $obj->user_refund; //请求地址
                $data['mer_cust_id'] = $hui_pay_config->mer_cust_id; //商户客户号
                $data['user_cust_id'] = $hui_pay_merchant->user_cust_id; //用户客户号
                $data['private_key'] = $hui_pay_config->private_key;
                $data['public_key'] = $hui_pay_config->public_key;
                $data['org_id'] = $hui_pay_config->org_id;
                $data['out_trade_no'] = $order->out_trade_no; //订单号
                $data['refund_amount'] = $refundFee_yuan; //退款金额
                $data['device_id'] = $hui_pay_merchant->device_id??''; //机具id
                $data['trade_no'] = $order->trade_no; //支付订单号
                $return = $obj->refund($data); //0-系统错误 1-成功 2-退款中 3-失败
//                Log::info('收钱啦-汇付-退款');
//                Log::info(str_replace("\\/", "/", json_encode($return, JSON_UNESCAPED_UNICODE)));
                //退款请求成功
                if ($return["status"] == '1') {
                    if (isset($return['data']) && !empty($return['data'])) {
                        $return_data = $return['data'];
                    }
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no); //更新订单状态

                    //退款成后更新退款表
                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //工行 退款
            if (19999 < $type && $type < 20999) {
                $config = new LianfuConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['appid'] = $h_merchant->appid; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['total_amount'] = $refund_amount; //
                $return = $obj->refund($data);
                if ($return['status'] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //海科融通 退款
            if (21999 < $type && $type < 22999) {
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通配置不存在请检查配置'
                    ]);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_return_data = [
                    'access_id' => $hkrt_config->access_id,
                    'refund_amount' => $refund_amount, //退款金额,(银联二维码只能全额退款)退款金额，以元为单位
                    'trade_no' => $order->trade_no, //SaaS平台的交易订单编号
                    'out_trade_no' => $order->out_trade_no,
                    'notify_url' => url('/api/hkrt/refund_notify_url'), //回调地址
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('海科融通-收钱啦-退款');
//                Log::info($hkrt_return_data);
                $return = $obj->refund($hkrt_return_data); //0-系统错误 1-成功 2-失败 3-结果未知
//                Log::info($return);

                //退款成功
                if ($return['status'] == 1) {
                    $hkrt_refund_no = $return['data']['refund_no']; //SaaS平台的退款订单编号
                    $refund_amount = $return['data']['refunded_amount']; //已退款金额
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $hkrt_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == '2'){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //未知
                elseif($return['status'] == '3') {
                    //TODO: 退款状态未知，先让收钱啦显示成功
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //易生支付 退款
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }
                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付配置不存在请检查配置'
                    ]);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付商户号不存在'
                    ]);
                }

                //当天的交易只能全额撤销,日切时间为渠道服务器的00:00；非当日才可退款
                $obj = new \App\Api\Controllers\Easypay\PayController();
                $now_time_start = strtotime(date('Y-m-d 00:00:00', time()));
                $now_time_end = strtotime(date('Y-m-d 23:59:59', time()));
                $order_pay_time = strtotime($order->pay_time);

                if (($order_pay_time > $now_time_start) && ($order_pay_time <= $now_time_end)) {
                    $easypay_revoke_data = [
                        'channel_id' => $easypay_config->channel_id, //渠道编号
                        'mno' => $easypay_merchant->termMercode, //终端商戶编号
                        'device_id' => $easypay_merchant->termTermcode, //终端编号
                        'out_trade_no' => $out_trade_no, //订单号
                        'trade_no' => $order->trade_no //系统订单号
                    ];
//                    Log::info('收钱啦易生支付-当日交易撤销');
//                    Log::info($easypay_revoke_data);
                    $return = $obj->order_close($easypay_revoke_data); //-1 系统错误 0-其他 1-成功
//                    Log::info($return);

                    //成功
                    if ($return['status'] == '1') {
                        $easypay_refund_no = $return['data']['oriwtorderid']; //撤销的商户订单号
                        $refund_amount = isset($return['data']['clearamt'])? ($return['data']['clearamt'] / 100) : $order->total_amount; //结算金额，单位分
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $easypay_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $easypay_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $easypay_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } //其他情况 退款失败
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL'; //
                        $re_data['return_msg'] = $message;
                    }
                } else {
                    $easypay_return_data = [
                        'channel_id' => $easypay_config->channel_id, //渠道编号
                        'mer_id' => $easypay_merchant->termMercode, //终端商戶编号
                        'term_id' => $easypay_merchant->termTermcode, //终端编号
                        'out_trade_no' => $order->out_trade_no, //商户订单号
                        'trade_no' => $order->trade_no, //原交易的系统订单号
                        'refund_amount' => $refund_amount, //退款金额,以元为单位
                    ];
//                    Log::info('易生支付-收钱啦-退款');
//                    Log::info($easypay_return_data);
                    $return = $obj->refund($easypay_return_data); //-1 系统错误 0-其他 1-成功 2-失败
//                    Log::info($return);

                    $easypay_refund_no = $return['data']['oriwtorderid']; //易生退货单号

                    //退款成功
                    if ($return['status'] == '1') {
                        $refund_amount = $order->total_amount; //已退款金额
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $easypay_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $easypay_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $easypay_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } //退款失败
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $message;
                    }
                }
            }


            //国通支付-退款
            if(in_array($type,[62001,62002,62004,62011,62012,62014])){
                $params = [
                    'config_id' => $config_id,
                    'store_id' => $store_id,
                    'store_pid' => $store_pid,
                    'out_trade_no' => $out_trade_no,
                    'refund_amount' => $refund_amount,
                    'new_refund_amount' => $new_refund_amount,
                    'new_fee_amount' => $new_fee_amount,
                    'ways_type' => $type,
                    'merchant_id' => $merchant_id,
                ];
                $result=BizService::gtxy_refund($order,$params,$this);
                $result=json_decode($result,true);
                if ($return['status'] == '1') {
                    $refund_amount = $order->total_amount; //已退款金额
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $easypay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $easypay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //邮储 退款
            if (26000 < $type && $type < 26999) {
                $config = new LianfuyoupayConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfuyouzheng\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['pos_sn'] = $h_merchant->pos_sn; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['refund_no'] = time(); //
                $data['pay_amount'] = $refund_amount; //
                $data['goods_name'] = '商品'; //

                $return = $obj->refund($data);

                if ($return['status'] == 1) {
                    //退款请求成功
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //葫芦天下
            if (22999 < $type && $type < 23999) {
                $manager = new \App\Api\Controllers\Hltx\ManageController();

                $hltx_merchant = $manager->pay_merchant($store_id, $store_pid);
                $qd = $hltx_merchant->qd;
                $hltx_config = $manager->pay_config($config_id, $qd);
                if (!$hltx_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => 'HL支付配置不存在请检查配置'
                    ]);
                }

                $manager->init($hltx_config);
                switch ($type) {
                    case 23001:
                        $pay_channel = 'ALI';
                        break;
                    case 23002:
                        $pay_channel = 'WX';
                        break;
                    case 23004:
                        $pay_channel = 'UPAY';
                        break;
                    default:
                        $pay_channel = 'ALI';
                        break;
                }

                if (!$hltx_merchant || empty($hltx_merchant->mer_no)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户未成功开通HL通道!'
                    ]);
                }

                $OutRefundNo = "hltx" . date('YmdHis') . str_pad(rand(0, 9999), 4, 0);
                $hltx_data = [
                    'merNo' => $hltx_merchant->mer_no,
                    'amount' => $refund_amount * 100,
                    'orderNo' => $OutRefundNo,
                    'oriOrderNo' => $out_trade_no,
                    'orderInfo' => '用户退款',
                    'deviceIp' => \EasyWeChat\Kernel\Support\get_client_ip()
                ];
                $return = $manager->refund_order($hltx_data);
                if ($return['status'] == 1) {
                    $return = $return['data'];
                    if ($return['tradeStatus'] == 'S' || $return['tradeStatus'] == 'R') {
                        //退款请求成功
                        $insert_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => 3,
                            'status' => 3,
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $OutRefundNo, //退款单号
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo
                        ]);
                        $re_data['result_code'] = 'SUCCESS';
                        $re_data['result_msg'] = '退款成功';
                        $re_data['refundNo'] = $OutRefundNo;
                        $re_data['refundFee'] = $refund_amount * 100;

                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                        $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    }
                    /*elseif($return['tradeStatus']=='R'){
                        $message = '等待退款';
                        //退款失败
                        $re_data['result_code'] = 'USERPAYING';
                        $re_data['result_msg'] = $message;
                        $re_data['refundNo'] = $OutRefundNo;
                        $re_data['refundFee'] = intval($refund_amount * 100).'';
                        $number=5;
                        for($i=0;$i<$number;$i++){
                            sleep(1);
                            \App\Common\Log::write('退款中查询','refund.log');
                            $hltx_data=[
                                'merNo'=>$hltx_merchant->mer_no,
                                'orderNo'=>$OutRefundNo,
                            ];
                            $query_result=$manager->query_order($hltx_data);
                            \App\Common\Log::write($query_result,'refund.log');
                            if($query_result['status']==1){
                                $query_result=$query_result['data'];
                                if($query_result['tradeStatus']=='R'){
                                    if($query_result['subTradeStatus']=='REFUNDING'){
                                        continue;
                                    }elseif($query_result['subTradeStatus']=='FAILED'||$query_result['subTradeStatus']=='SYS_FAILED'){
                                        $message = '退款失败';
                                        //退款失败
                                        $re_data['result_code'] = 'FALL';
                                        $re_data['result_msg'] = $message;
                                        break;
                                    }elseif($query_result['subTradeStatus']=='COMPLETE'){
                                        $insert_data = [
                                            'status' => 6,
                                            'pay_status' => 6,
                                            'pay_status_desc' => '已退款',
                                            'fee_amount' => 0,
                                            'refund_amount' => $refund_amount
                                        ];
                                        $this->update_day_order($insert_data, $out_trade_no);

                                        RefundOrder::create([
                                            'pay_status' => 3,
                                            'status' => 3,
                                            'type' => $type,
                                            'ways_source' => $order->ways_source,
                                            'status_desc' => '退款',
                                            'refund_amount' => $refund_amount, //退款金额
                                            'refund_no' => $OutRefundNo, //退款单号
                                            'store_id' => $store_id,
                                            'merchant_id' => $store->merchant_id,
                                            'out_trade_no' => $order->out_trade_no,
                                            'trade_no' => $order->trade_no
                                        ]);

                                        $re_data['result_code'] = 'SUCCESS';
                                        $re_data['result_msg'] = '退款成功';
                                        $re_data['refundNo'] = $OutRefundNo;
                                        $re_data['refundFee'] = $refund_amount * 100;
                                        break;
                                    }
                                }elseif($query_result['tradeStatus']=='S'){
                                    if($query_result['subTradeStatus']=='COMPLETE'){
                                        $insert_data = [
                                            'status' => 6,
                                            'pay_status' => 6,
                                            'pay_status_desc' => '已退款',
                                            'fee_amount' => 0,
                                            'refund_amount' => $refund_amount
                                        ];
                                        $this->update_day_order($insert_data, $out_trade_no);

                                        RefundOrder::create([
                                            'pay_status' => 3,
                                            'status' => 3,
                                            'type' => $type,
                                            'ways_source' => $order->ways_source,
                                            'status_desc' => '退款',
                                            'refund_amount' => $refund_amount, //退款金额
                                            'refund_no' => $OutRefundNo, //退款单号
                                            'store_id' => $store_id,
                                            'merchant_id' => $store->merchant_id,
                                            'out_trade_no' => $order->out_trade_no,
                                            'trade_no' => $order->trade_no
                                        ]);

                                        $re_data['result_code'] = 'SUCCESS';
                                        $re_data['result_msg'] = '退款成功';
                                        $re_data['refundNo'] = $OutRefundNo;
                                        $re_data['refundFee'] = $refund_amount * 100;
                                        break;
                                    }
                                }else{
                                    break;
                                }
                            }else{
                                break;
                            }
                        }
                    }*/
                    else {
                        $message = '退款失败';
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $message;
                    }
                } else {
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联动优势 退款
            if (4999 < $type && $type < 5999) {
                // $config = new LinkageConfigController();
                // $linkage_config = $config->linkage_config($config_id);
                // if (!$linkage_config) {
                //     return json_encode([
                //         'status' => '2',
                //         'message' => '联动优势支付配置不存在，请检查配置'
                //     ]);
                // }

                // $linkage_merchant = $config->linkage_merchant($store_id, $store_pid);
                // if (!$linkage_merchant) {
                //     return json_encode([
                //         'status' => '2',
                //         'message' => '联动优势商户号不存在'
                //     ]);
                // }

                //针对交易当天的成功订单可以进行撤销，过了账期则需要走退费接口。仅支持微信支付宝刷卡交易（即用户被扫）的撤销，其他支付成功订单如需实现相同功能请调用3.5退款请求接口
                $obj = new \App\Api\Controllers\Linkage\PayController();
                $now_time_start = strtotime(date('Y-m-d 00:00:00', time()));
                $now_time_end = strtotime(date('Y-m-d 23:59:59', time()));
                $order_pay_time = strtotime($order->pay_time);

                $linkage_revoke_data = [
                    'out_trade_no' => $out_trade_no, //订单号
                    'out_refund_no' => time(),
                ];
                $return = $obj->refund($linkage_revoke_data);
                
                //成功
                if ($return['status'] == '1') {
                    $refund_amount = $order->total_amount;
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => '6',
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $out_trade_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                 //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$out_trade_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $out_trade_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $out_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                }
                else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }

            //威富通 退款
            if (26999 < $type && $type < 27999) {
                $config = new WftPayConfigController();

                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付配置不存在，请检查配置'
                    ]);
                }
                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付商户号不存在'
                    ]);
                }

                $wftpay_return_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'total_amount' => $order->total_amount,
                    'refund_fee' => $refund_amount,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通-收钱啦-退款-入参');
//                Log::info($wftpay_return_data);
                $obj = new WftPayPayController();
                $return = $obj->refund($wftpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('威富通-收钱啦-退款');
//                Log::info($return);

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $wftpay_refund_no = isset($return['data']['out_refund_id_'.$refund_count]) ?$return['data']['out_refund_id_'.$refund_count]: $return['data']['refund_id_'.$refund_count]; //第三方退款单号
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }

            //汇旺财 退款
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付配置不存在，请检查配置'
                    ]);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付商户号不存在'
                    ]);
                }

                $hwcpay_return_data = [
                    'mch_id' => $hwcpay_merchant->mch_id, //门店号
                    'merchant_num' => $hwcpay_merchant->merchant_num, //商户号
                    'out_trade_no' => $out_trade_no,
                    'total_amount' => $order->total_amount,
                    'refund_fee' => $refund_amount,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财-收钱啦-退款-入参');
//                Log::info($hwcpay_return_data);
                $obj = new HwcPayPayController();
                $return = $obj->refund($hwcpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('汇旺财-收钱啦-退款');
//                Log::info($return);
                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $hwcpay_refund_no = isset($return['data']['out_refund_id_'.$refund_count])? $return['data']['out_refund_id_'.$refund_count]: $return['data']['refund_id_'.$refund_count]; //第三方退款单号
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $hwcpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$hwcpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $hwcpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $hwcpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //
                    $re_data['return_msg'] = $message;
                }
            }
            //银联商务退款
            if(in_array($type,[30020,30021,30022,30023,30024,30025])){
                $config = new MerchConfigController();
                $h_merchant = $config->merch_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '银联商务商户号不存在'
                    ]);
                }

                $return_data = [
                    'merchantCode' => $h_merchant->MerchantId,
                    'terminalCode' => $h_merchant->merchzhongduanid,
                    'merchantOrderId' => $out_trade_no,
                    'refundRequestId' => $out_trade_no,
                    'transactionAmount' => intval($order->total_amount*100)
                ];
                $obj = new WftPayPayController();
                if(in_array($type,[30020,30021,30022,])){
                    $return = $obj->refund1($h_merchant->accessToken,$return_data);
                }else if(in_array($type,[30023,30024,30025])){
                    $return_data["appId"] = $h_merchant->merch_appid;
                    $return_data["appKey"] = $h_merchant->merch_appkey;
                    $return_data["store_id"] = $store_id;
                    $return = $obj->refundV6($return_data);
//                    $return = $obj->voidPaymentV6($return_data);
                }

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $wftpay_refund_no = isset($return['data']['out_refund_id_'.$refund_count]) ?$return['data']['out_refund_id_'.$refund_count]: $return['data']['refund_id_'.$refund_count]; //第三方退款单号
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }
            
            //平安银行退款
            if (30011 == $type || 30012 == $type || 30013 == $type) {
                $config = new PinganConfigController();
                $h_merchant = $config->pingan_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '平安银行商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $pingan_data['third_order_id']=$order->trade_no;
                $pingan_data['enterpriseReg']=$h_merchant->enterpriseReg;
                $pingan_data['merchant_id']=$h_merchant->merchant_id;
                $pingan_data['refundMsg']='tkmtk';
                $pingan_data['refund_amount']=$order->total_amount;
                
                foreach (array_filter($pingan_data) as $k => $v){
                    $Parameters[$k] = $v;
                }
                $buff = "";
                ksort($Parameters);
                foreach ($Parameters as $k => $v) {
                    $buff .= $k . "=" . $v . "&";
                }
                $String = '';
                if (strlen($buff) > 0) {
                    $String = substr($buff, 0, strlen($buff) - 1);
                }
                $String = $String . $h_merchant->appsecret;
                $re=hash('sha256', $String, true);
                $String = strtoupper(bin2hex($re));
                
                $json='{"appid":"'."$h_merchant->appid".'"'.',"timeStamp":"'.time().'000'.'"'.',"data":'.stripslashes(json_encode($pingan_data,JSON_UNESCAPED_SLASHES)).',"sign":"'.$String.'"'.'}';
                $return = $obj->refund6($json);

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = 1; //退款记录数
                    $wftpay_refund_no = $return['data']['refNum']; //第三方退款单号
                    $refund_amount = $order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }

            //通联支付退款
            if (32000 == $type || 32001 == $type || 32002 == $type) {
                $config = new AllinpayConfigController();
                $h_merchant = $config->allinpay_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '通联支付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                if($h_merchant->orgid){
                    $wftpay_data['orgid'] = $h_merchant->orgid;//机构号
                }
                $wftpay_data = [
                    'cusid' => $h_merchant->cusid,
                    'appid' => $h_merchant->appid,
                    'version' => '11',
                    'trxamt' => bcmul($refund_amount,100),
                    'reqsn' => 'tk'.rand(10000,99999).time(),
                    'oldtrxid' => $order->trade_no,
                    'randomstr' => time(),
                    'signtype' => 'RSA',
                ];
                $return = $obj->allin_refund($wftpay_data,$h_merchant->prikey);

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = 1; //退款记录数
                    $wftpay_refund_no = $return['data']['trxid']; //第三方退款单号
                    $refund_amount = $order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }
            
            //扫呗 退款
            if (30080 == $type || 30081 == $type || 30082 == $type) {
                $config = new SaobeiConfigController();
                $h_merchant = $config->saobei_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '扫呗商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $wftpay_data = [
                    'pay_ver' => '100',
                    'pay_type' => '000',
                    'service_id' => '030',
                    'merchant_no' => $h_merchant->merchantNo,
                    'terminal_id' => $h_merchant->zhongduan,
                    'terminal_trace' => time().round(10000,99999),
                    'terminal_time'=>date('YmdHis', time()),
                    'refund_fee'=>bcmul($refund_amount,100),
                    'out_trade_no'=>$order->trade_no
                ];
                $return = $obj->refund3($wftpay_data,$h_merchant->access_token);

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = 1; //退款记录数
                    $wftpay_refund_no = $return['data']['trxid']; //第三方退款单号
                    $refund_amount = $order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }

            //聚合支付logic-退款
            $company = ucfirst($order->company);
            if (method_exists("App\Api\Controllers\\$company\LogicController",'refundParams')) {

                try {
                    $refund_no = $out_trade_no.'1';
                    $params = [
                        'config_id' => $config_id,
                        'store_id' => $store_id,
                        'store_pid' => $store_pid,
                        'out_trade_no' => $out_trade_no,
                        'refund_no' => $refund_no,
                        'refund_amount' => $refund_amount,
                        'new_refund_amount' => $new_refund_amount,
                        'new_fee_amount' => $new_fee_amount,
                        'ways_type' => $order->ways_type,
                        'merchant_id' => $merchant_id,
                        'trade_no' => $order->trade_no
                    ];
                    $class = "\\App\\Api\\Controllers\\$company\\LogicController";
                    $return = json_decode((new $class)->refundParams($params, $order), true);
                    error_log(date('Y-m-d H:i:s')." 【mergePay】： ".json_encode([$return])."\n\n", 3, "/tmp/". 'mergePay'.date('Ymd').".log");

                    //退款成功
                    if ($return['status'] == 1) {
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } //失败
                    elseif($return['status'] == 2){
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = '退款失败';
                    } //其他
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL'; //退款失败
                        $re_data['return_msg'] = $message;
                    }
                } catch (\Exception $exception) {

                    error_log(date('Y-m-d H:i:s')." 【mergePay】： ".json_encode([$exception->getMessage()])."\n\n", 3, "/tmp/". 'mergePay'.date('Ymd').".log");

                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $ex) {
            Log::info('收钱啦-退款error');
            Log::info($ex->getMessage() .' | '.$ex->getFile().' | '. $ex->getLine());
            $re_data = [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage() .' | '. $ex->getLine()
            ];
            return $this->return_data($re_data);
        }
    }


    /**
     * 退款查询
     *
     * 提交退款申请后，通过调用该接口查询退款状态。退款有一定延时，用零钱支付的退款20分钟内到账， 银行卡支付的退款3个工作日后重新查询退款状态
     * @param $data
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function refund_query($data)
    {
        try {
            Log::info('收钱啦-退款查询-入参');
            Log::info($data);

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = $data['device_id'] ?? ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //否,String(32),商户订单号
            $transaction_id = $data['transaction_id'] ?? ''; //否,String(32),平台交易号
            $out_refund_no = $data['out_refund_no'] ?? ''; //否,String(32),商户退款单号,32个字符内、可包含字母,确保在商户系统唯一
            $refund_id = $data['refund_id'] ?? ''; //否,String(32),平台退款单号(refund_id、out_refund_no、out_trade_no、transaction_id四个参数必填一个，如果同时存在优先级为：refund_id>out_refund_no>transaction_id>out_trade_no)

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            //调用系统前参数
            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
            }

            //如果订单号为空或者不存在
            if (!$order) {
                Log::info('收钱啦-查询订单-无果：');
                Log::info($out_trade_no);
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }

            //上线后去掉开始
            $refund = RefundOrder::where('out_trade_no', $order->out_trade_no)
                ->select('refund_no')
                ->first();

            //如果订单号为空或者不存在
            if (!$refund) {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '退款订单号不存在';
                return $this->return_data($re_data);
            }
            $refundNo = $refund->refund_no;
            //上线后去掉结束

            $channel = '';
            if ($order->ways_type == 1001) {
                $channel = 'ali_barcode_pay';
            }

            if ($order->ways_type == 2001) {
                $channel = "wx_barcode_pay";
            }

            $re_data = [
                'version' => '1.0.0', //版本号
                'charset' => 'UTF-8', //字符集
                'sign_type' => 'MD5', //签名类型，取值：MD5
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
                'return_msg' => '', //否,String(128),返回信息，如非空，为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //String(8),业务结果 SUCCESS/FAIL
                'nonce_str' => $this->nonceStr() //String(32),随机字符串
            ];

            $type = $order->ways_type;
            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id')
                ->first();
            $config_id = $store->config_id;
            $store_pid = $store->pid;
            $out_trade_no = $order->out_trade_no;

            //官方支付宝查询
            if (999 < $type && $type < 1999) {
                $config = AlipayIsvConfig::where('config_id', $config_id)
                    ->where('config_type', '01')
                    ->first();

                //获取token
                $storeInfo = AlipayAppOauthUsers::where('store_id', $data['merchantId'])
                    ->select('app_auth_token')
                    ->first();

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.fastpay.refund.query';
                $requests = new AlipayTradeFastpayRefundQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"," .
                    "    \"out_request_no\":\"" . $refundNo . "\"" .
                    "  }");
                $refund = $aop->execute($requests, '', $storeInfo->app_auth_token);

                //支付成功
                if ($refund->alipay_trade_fastpay_refund_query_response->code == 10000) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->out_request_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->out_request_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $order->updated_at); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $message = $refund->alipay_trade_fastpay_refund_query_response->sub_msg;
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = $message;
                }
            }

            //微信官方扫码
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;
                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], // XXX: 绝对路径！！！！
                    'key_path' => $options['payment']['key_path'],     // XXX: 绝对路径！！！！
                    'sub_mch_id' => $wx_sub_merchant_id,
                    // 'device_info'     => '013467007045764',
                    // 'sub_app_id'      => '',
                    // ...
                ];

                $payment = Factory::payment($config);
                $refund_query = $payment->refund->queryByOutTradeNumber($order->out_trade_no);
                if ($refund_query['return_code'] == "SUCCESS") {
                    //退款成功
                    if ($refund_query['result_code'] == "SUCCESS") {
                        $refund_count = $refund_query['refund_count'];
                        $refund_count_num = $refund_count - 1;
                        $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['refund_count'] = $refund_count; //int,退款记录数
                        $re_data['out_refund_no_'.$refund_count_num] = $refund_query['refund_status_'.$refund_count_num]; //String(32),商户退款单号
                        $re_data['refund_id_'.$refund_count_num] = $refund_query['refund_status_'.$refund_count_num]; //String(32),平台退款单号
                        $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                        $re_data['refund_fee_'.$refund_count_num] = $refund_query['refund_fee']; //int,退款总金额,单位为分,可以做部分退款
                        $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $refund_query['refund_success_time_'.$refund_count_num]); //否,String(14),退款时间,yyyyMMddHHmmss
                    } else {
                        //
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $refund_query['result_msg'];
                    }
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $refund_query['return_msg'];
                }
            }

            //京东收银支付退款查询
            if (5999 < $type && $type < 6999) {
                //读取配置
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['request_url'] = $obj->refund_query_url; //请求地址;
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $data['outRefundNo'] = $refundNo;
                $return = $obj->refund_query($data);
                //退款成功
                if ($return["status"] == 1) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['amount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联拓富收银支付退款查询
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();

                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['request_url'] = $obj->refund_query_url; //请求地址;
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $data['outRefundNo'] = $refundNo;
                $return = $obj->refund_query($data);
                //退款成功
                if ($return["status"] == 1) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['refundAmount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['time'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //快钱支付
            if (2999 < $type && $type < 3999) {
                //读取配置
                $config = new MyBankConfigController();
                $mybank_merchant = $config->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $wx_AppId = $mybank_merchant->wx_AppId;
                $MyBankConfig = $config->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $aop = new \App\Api\Controllers\MyBank\BaseController();
                $ao = $aop->aop($config_id);
                $ao->url = $aop->MY_BANK_request2;
                $ao->Function = "ant.mybank.bkmerchanttrade.refundQuery";
                $data = [
                    'MerchantId' => $mybank_merchant->MerchantId,
                    'OutRefundNo' => $refundNo,
                ];
                $re = $ao->Request($data);
                if ($re['status'] == 0) {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $re['msg'];
                    return $this->return_data($re_data);

                }

                $body = $re['data']['document']['response']['body'];
                $Result = $body['RespInfo'];
                //支付成功
                if ($Result['ResultStatus'] == "S") {
                    $GmtRefundment = $body['GmtRefundment'];

                    //退款成功
                    if ($body['TradeStatus'] == "succ") {
                        $refund_count = 1;
                        $refund_count_num = $refund_count - 1;
                        $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['refund_count'] = $refund_count; //int,退款记录数
                        $re_data['out_refund_no_'.$refund_count_num] = $body['OutRefundNo']; //String(32),商户退款单号
                        $re_data['refund_id_'.$refund_count_num] = $body['OutRefundNo']; //String(32),平台退款单号
                        $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                        $re_data['refund_fee_'.$refund_count_num] = $body['RefundAmount']; //int,退款总金额,单位为分,可以做部分退款
                        $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $GmtRefundment); //否,String(14),退款时间,yyyyMMddHHmmss
                    }

                    //退款中
                    if ($body['TradeStatus'] == "refunding") {
                        $re_data['result_code'] = 'USERPAYING';
                        $re_data['return_msg'] = '退款中';
                        $re_data['refundNo'] = $refundNo;
                    }

                    //失败
                    if ($body['TradeStatus'] == "fail") {
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = '退款失败';
                        $re_data['refundNo'] = $refundNo;
                    }
                } else {
                    //其他情况
                    $message = $Result['ResultMsg'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //和融通
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //暂时用查询代替
                $data['mid'] = $h_merchant->h_mid;
                $data['md_key'] = $h_config->md_key; //
                $data['orgNo'] = $h_merchant->orgNo; //
                $return = $obj->order_query($data); //暂时用查询代替
                //退款成功
                if ($return["status"] == 4) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['amount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 5) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //传化
            if (11999 < $type && $type < 12999) {
                //读取配置
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $data = [];
                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['refund_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $return = $obj->refund_query($data); //暂时用查询代替

                //退款成功
                if ($return["status"] == 4) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['refund_fee']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', time()); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 5) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付支付退款
            if (12999 < $type && $type < 13999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '随行付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '随行付商户号不存在';

                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->refund_query($data);

                //退款成功
                if ($return["status"] == 1) {
                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['return_msg'] = '退款成功';
                    $re_data['refundNo'] = $refundNo;
                    $re_data['refundTime'] = date('Y-m-d H:i:s', time());
                    $re_data['refund_count'] = '1';

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $order->total_amount; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', time()); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '正在查询退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;

                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //海科融通 退款查询
            if (21999 < $type && $type < 22999) {
                //读取配置
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '海科融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '海科融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_return_data = [
                    'access_id' => $hkrt_config->access_id,
                    'refund_no'  => $refundNo, //退款订单号,refund_no和 out_refund_no和channel_trade_no必传其中一个，三个都传则以refund_no为准，推荐使用refund_no
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('收钱啦-海科融通-退款查询-入参');
//                Log::info($hkrt_return_data);
                $return = $obj->refund_query($hkrt_return_data); //0-系统错误 1-成功 2-失败 3-未知
//                Log::info('收钱啦-海科融通-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $hkrt_refund_amount = $return['data']['refund_amount']; //退款金额
                    $hkrt_total_amount = $return['data']['total_amount']; //原消费交易总金额
                    $hkrt_remanent_amount = $return['data']['remanent_amount']; //剩余可退款金额
                    $hkrt_refund_no = $return['data']['refund_no']; //SaaS平台的退款订单编号
                    $hkrt_return_time = $return['data']['trade_end_time']; //SaaS平台交易完成时间，交易完成以后会返回

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $hkrt_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $hkrt_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $hkrt_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $hkrt_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //易生支付 退款查询
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                    //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }
                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '易生支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '易生支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Easypay\PayController();
                $easypay_return_data = [
                    'channel_id' => $easypay_config->channel_id,
                    'mer_id' => $easypay_merchant->termMercode,
                    'device_id' => $easypay_merchant->termTermcode,
                    'out_trade_no' => $order->out_trade_no,
                    "private_key"=>$easypay_config->private_key
                ];
//                Log::info('收钱啦-易生支付-退款查询-入参');
//                Log::info($easypay_return_data);
                $return = $obj->order_query($easypay_return_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//                Log::info('收钱啦-易生支付-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $easypay_refund_no = $return['data']['oriwtorderid']; //易生退货单号
                    $easypay_refund_amount = $order->total_amount; //退款金额
                    $easypay_total_amount = $order->total_amount; //原消费交易总金额
                    $easypay_return_time = $order->pay_time; //交易完成时间

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $easypay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $easypay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $easypay_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $easypay_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            // 国通支付 交易查询  gtxy
            if(in_array($type,[62001,62002,62004,62011,62012,62014])){
                $return= BizService::gtxy_query($order,$store,"",$this);
                $return=json_decode($return,true);
//                'ways_source' => $order->ways_source,
//                    'pay_time' => $pay_time,
//                    'out_trade_no' => $order->out_trade_no,
//                    'pay_amount' => $payamt,
//                    'total_amount' => $order->total_amount,
//                    'other_no' => $other_no,
//                    'trade_no' => $trade_no
                if ($return['status'] == '1') {
                    $linkage_refund_no = $return['data']['trade_no']??""; //退款流水号
                    $linkage_trade_no = $return['data']['trade_no']??""; //联动流水号
                    $linkage_refund_amount = $return['data']['total_amount']??""; //退款金额
                    $linkage_total_amount = $order->total_amount; //原消费交易总金额
                    $linkage_return_time = $order->pay_time; //交易完成时间

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id??""; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no??""; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count??""; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $linkage_refund_no??""; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $linkage_trade_no??""; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $linkage_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $linkage_return_time??time()); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }

            }
            //联动优势 退款查询
            if (4999 < $type && $type < 5999) {
                $config = new LinkageConfigController();
                $linkage_config = $config->linkage_config($config_id);
                if (!$linkage_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '联动优势支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $linkage_merchant = $config->linkage_merchant($store_id, $store_pid);
                if (!$linkage_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '联动优势支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Linkage\PayController();
                $linkage_return_data = [
                    'channel_id' => $linkage_config->channel_id,
                    'mer_id' => $linkage_merchant->termMercode,
                    'device_id' => $linkage_merchant->termTermcode,
                    'out_trade_no' => $order->out_trade_no
                ];
//                Log::info('收钱啦-联动优势支付-退款查询-入参');
//                Log::info($linkage_return_data);
                $return = $obj->refund_query($linkage_return_data); //-1系统错误；0-其他；1-成功；2-验签失败；3-失败；4-处理中
//                Log::info('收钱啦-联动优势支付-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $linkage_refund_no = $return['data']['orderNo']; //退款流水号
                    $linkage_trade_no = $return['data']['transactionId']; //联动流水号
                    $linkage_refund_amount = $return['data']['txnAmt']; //退款金额
                    $linkage_total_amount = $order->total_amount; //原消费交易总金额
                    $linkage_return_time = $order->pay_time; //交易完成时间

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $linkage_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $linkage_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $linkage_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $linkage_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //威富通 退款查询
            if (26999 < $type && $type < 27999) {
                $config = new WftPayConfigController();
                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '威富通支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '威富通支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new WftpayPayController();
                $wftpay_return_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $order->out_trade_no,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通支付-收钱啦-退款查询-入参');
//                Log::info($wftpay_return_data);
                $return = $obj->refund_query($wftpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('威富通支付-收钱啦-退款查询');
//                Log::info($return);
                //退款请求成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $wftpay_refund_no = $return['data']['out_refund_no_'.$refund_count] ?? ''; //商户退款单号
                    $wftpay_trade_no = $return['data']['out_refund_id_'.$refund_count] ?? ''; //第三方退款单号
                    $wftpay_refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100): $order->total_amount; //退款总金额,单位为分,可以做部分退款
                    $wftpay_total_amount = $order->total_amount; //原消费交易总金额
                    $wftpay_return_time = $order->pay_time; //交易完成时间
                    $pay_time = isset($return['data']['refund_time_'.$refund_count]) ? date('Y-m-d H:i:s', strtotime($return['data']['refund_time_'.$refund_count])): ''; //退款时间

                    if ($order->pay_status != 6) {
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '退款成功',
                            'refund_no' => $wftpay_refund_no,
                            'refund_amount' => $wftpay_refund_amount
                        ];
                        if ($pay_time) $insert_data['pay_time'] = $pay_time;
                        $this->update_day_order($insert_data, $out_trade_no, '');

                        //退款成功后的动作
                        $refund_order_obj = RefundOrder::where('out_trade_no', $out_trade_no)->first();
                        if (!$refund_order_obj) {
                            $return_data = [
                                'out_trade_no' => $out_trade_no,
                                'trade_no' => $order->trade_no,
                                'store_id' => $order->store_id,
                                'merchant_id' => $order->merchant_id,
                                'type' => $order->ways_type,
                                'ways_source' => $order->ways_source,
                                'refund_amount' => $wftpay_refund_amount,
                                'refund_no' => $wftpay_refund_no ?? $wftpay_trade_no
                            ];
                            RefundOrder::create($return_data);
                            //退款成功后的操作
                            RefundSuccessAction::action([
                                'out_trade_no'=>$out_trade_no,
                                'refund_no' =>$return_data["refund_no"], //平台退款单号
                            ]);
                        }
                    }

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $wftpay_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $wftpay_refund_amount*100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($wftpay_return_time)); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //汇旺财 退款查询
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '汇旺财支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '汇旺财支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new HwcPayPayController();
                $hwcpay_return_data = [
                    'mch_id' => $hwcpay_merchant->mch_id,
                    'out_trade_no' => $order->out_trade_no,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财支付-收钱啦-退款查询-入参');
//                Log::info($hwcpay_return_data);
                $return = $obj->refund_query($hwcpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('汇旺财支付-收钱啦-退款查询');
//                Log::info($return);
                //退款请求成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $hwcpay_refund_no = $return['data']['out_refund_no_'.$refund_count]; //商户退款单号
                    $hwcpay_trade_no = $return['data']['out_refund_id_'.$refund_count]; //第三方退款单号
                    $hwcpay_refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //退款总金额,单位为分,可以做部分退款
                    $hwcpay_total_amount = $order->total_amount; //原消费交易总金额
                    $hwcpay_return_time = $order->pay_time; //交易完成时间
                    $pay_time = isset($return['data']['refund_time_'.$refund_count]) ? date('Y-m-d H:i:s', strtotime($return['data']['refund_time_'.$refund_count])): ''; //退款时间

                    if ($order->pay_status != 6) {
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '退款成功',
                            'refund_no' => $hwcpay_refund_no,
                            'refund_amount' => $hwcpay_refund_amount
                        ];
                        if ($pay_time) $insert_data['pay_time'] = $pay_time;
                        $this->update_day_order($insert_data, $out_trade_no, '');

                        //退款成功后的动作
                        $refund_order_obj = RefundOrder::where('out_trade_no', $out_trade_no)->first();
                        if (!$refund_order_obj) {
                            $return_data = [
                                'out_trade_no' => $out_trade_no,
                                'trade_no' => $order->trade_no,
                                'store_id' => $order->store_id,
                                'merchant_id' => $order->merchant_id,
                                'type' => $order->ways_type,
                                'ways_source' => $order->ways_source,
                                'refund_amount' => $hwcpay_refund_amount,
                                'refund_no' => $hwcpay_refund_no ?? $hwcpay_trade_no
                            ];
                            RefundOrder::create($return_data);
                            //退款成功后的操作
                            RefundSuccessAction::action([
                                'out_trade_no'=>$out_trade_no,
                                'refund_no' =>$return_data["refund_no"], //平台退款单号
                            ]);
                        }
                    }

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $hwcpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $hwcpay_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $hwcpay_refund_amount*100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($hwcpay_return_time)); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $e) {
            Log::info('收钱啦-退款查询error');
            Log::info($e->getMessage() .' | '. $e->getFile() .' | '. $e->getLine());
            $re_data = [
                'return_code' => 'FALL',
                'return_msg' => $e->getMessage() .' | '. $e->getLine()
            ];
        }

        return $this->return_data($re_data);
    }
    
        /**
     * 32位随机数
     * @return string
     */
    public function nonceStr()
    {
        return md5(mt_rand(1000, 9999).time());
    }
    
    /**
	 * 计算签名，方式一
	 */
	public function signature($params = [],$appKey)
	{
		return bin2hex(hash('SHA256',$params['appId'].$params['timestamp'].$params['nonce'].$appKey,true));
	}
    
    //重置平台所有使用银联商务通道的商户的accessToken
    public function update_merch_token(){
        // $rate=DB::table('store_day_rate')->where('settling_day','2022-05-16')->select('*')->get();
        // $rate=json_decode($rate,true);
        // foreach ($rate as $k=>$v){
        //     unset($v['id']);
        //     DB::table('service_day_money')->insert($v);
        // }
        $merch_list = DB::table('merch_stores')->select('merch_appid', 'merch_appkey','store_id')->get();
        foreach($merch_list as $key=>$val){
            $nonce=$this->nonceStr();
            $appId=$val->merch_appid;
            $timestamp=date('YmdHis', time());
            $signMethod='SHA256';
            $appKey=$val->merch_appkey;
            $data_info=array(
                'appId'=>$appId,
                'timestamp'=>$timestamp,
                'nonce'=>$nonce,
                'signMethod'=>$signMethod,
            );
            $data_info['signature']=$this->signature($data_info,$appKey);
            $result = json_decode($this->curl_merch('https://api-mop.chinaums.com/v1/token/access' ,'POST',json_encode($data_info),['Content-type: application/json']),true);
            if(isset($result['accessToken'])){
                $res=DB::table('merch_stores')->where('store_id', $val->store_id)->update(array('accessToken'=>$result['accessToken']));
            }
        }
    }
    
    //激活银商终端
    public function yszhongduan(){
            $data_info=array(
                'merchantCode'=>'898341286991324',
                'terminalCode'=>'12424045',
            );
            $result = json_decode($this->curl_merch('https://api-mop.chinaums.com/v2/poslink/transaction/activeterminal' ,'POST',json_encode($data_info),['Content-type: application/json','Authorization:OPEN-ACCESS-TOKEN AccessToken='.'e4e7d797d4ef4dba890ff1e9714369bf']),true);
    }
    
    //农金每日激活终端
    public function zhongduan(){
        $nongjin_list = DB::table('nongjin_stores')->select('merchantNo', 'terminalNo','batchNo','store_id')->get();
        foreach($nongjin_list as $key=>$val){
            $post_data = [
                'merchantNo' => $val->merchantNo,
                'terminalNo' => $val->terminalNo
            ];
            $url = 'https://epos.ahrcu.com:3443/cposp/pay/signIn';
            $re = $this->http_curl($url, json_encode($post_data));
            $re = json_decode($re, true);
            if($re['resultCode']==00){
                DB::table('nongjin_stores')->where('store_id', $val->store_id)->update(array('batchNo'=>$re['batchNo']));
            }
        }
    }
    
    //翼支付商户重置
    public function wingmerch(){
        $obj = new \App\Api\Controllers\lianfu\PayController();
        $logid='cs324152443431';
        $data=array('merchantCode'=>'3178035738712625','businessServiceNo'=>'3178035630163868','institutionCode'=>'3178035630163868','traceLogId'=>$logid);
        $obj->upwingmerch($data);
    }
    
    //同步订单扣款
    public function ceshi(){
        // $where[] = ['created_at', '>=', '2023-05-05 00:00:00'];
        // $where[] = ['created_at', '<=', '2023-05-05 23:59:59'];
        // $orders = DB::table('csrders')->where($where)->orderBy('created_at', 'asc')->limit(2000)->get();
        // $orders=json_decode($orders,true);
        // foreach ($orders as $k=>$v){
        //     $id=$v['id'];
        //     unset($v['id']);
        //     DB::table('orders')->insert($v);
        //     DB::table('csrders')->where('id',$id)->delete();
        // }
        
        
        
        $array=array(
            'wx_qr20230927231448387167668',
            'wx_qr20230927231457805586022',
            'wx_qr20230927231508819110160',
            'wx_qr20230927231532974336044',
        );
        foreach($array as $k=>$v){
            DB::table('orders')->where('out_trade_no',$v)->update(['status'=>'1','pay_status'=>'1','pay_status_desc'=>'支付成功','trade_no'=>$v]);
        }
        // $where[] = ['created_at', '>=','2023-01-17 00:00:00'];
        // $where[] = ['created_at', '<=','2023-02-15 23:59:59'];
        // $order_count=DB::table('orders')->where('store_id','2021724102726632631')->where($where)->where('pay_status','1')->sum('fee_amount');
        // echo $order_count;
        // die;
        // $device = DB::table('devices')->where('id', '1157')->first();
        // $data=[];
        // $time = time();
        // $content = '<CB>付款回执</CB><BR>';
        // $content .= '--------------------------------<BR><BR>';
        // $content .= '商户名称:安徽皖付通<BR><BR>';
        // $content .= '交易时间:2022-10-26 10:55:60<BR><BR>';
        // $content .= '皖付通订单号:202265456464656<BR><BR>';
        // $content .= '原始订单号：44465464<BR><BR>';
        // $content .= '付款方式：微信<BR><BR>';
        // $content .= '款台名称：测试<BR><BR>';
        // $content .= '流水号：16346546466465<BR><BR>';
        // $content .= '合计：0.01元<BR>';
        // $content .= '--------------------------------<BR><BR>';
        // $content .= '签名：<BR><BR><BR>';
        // $content .= '<C>谢谢惠顾,欢迎下次光临</C>';
        // $content .= '<QR>https://pay.zgjindoufu.com/api/wincode/feie_nuonuo?out_trade_no=202265456464656</QR>';
        
        // $msgInfo = array(
        //   'user'=>'2067925302@qq.com',
        //   'stime'=>$time,
        //   'sig'=>sha1('2067925302@qq.com'.'2bjzLB3PQpTPC65Z'.$time),
        //   'apiname'=>'Open_printMsg',
        //   'sn'=>$device->device_no,
        //   'content'=>$content
        // );
        // $client=$this->feieyun('https://api.feieyun.cn/Api/Open/',$msgInfo);
        
        // $store_id='2022922161814756388';
        // $where[] = ['created_at', '>=','2022-10-26 00:00:00'];
        // $where[] = ['created_at', '<=','2022-10-26 23:59:59'];
        // $orderdata = Order::where($where)->where('store_id',$store_id)->where('pay_status',1)->get();
        // $orderdata=json_decode($orderdata,true);
        //             echo '<pre>';
        //     print_r($orderdata);
        //     die;
        // foreach ($orderdata as $k=>$v){
        //     // $res=Order::where('out_trade_no',$v['out_trade_no'])->update(array('fee_amount',$fee_amount));
        //     Order::where('out_trade_no', $v['out_trade_no'])->update(array('fee_amount'=>round($v['total_amount']*0.0008,2)));
        // }
        
//         $out_trade_no='wxWft20220422172800325869684';
//         $orderdata = Order::where('out_trade_no', $out_trade_no)->first()->toarray();
//         if($orderdata['company']=='wftpay' || $orderdata['company']=='nongjin' || $orderdata['company']=='pingan'){
//             echo '<pre>';
//             print_r(11);
//             die;
//         }
//         die;
//         $store=Store::where('store_id', $orderdata['store_id'])->first()->toarray();
//         $rata_money = $store['rata_store'] * $orderdata['total_amount'] / 100;
//         //判断该订单店铺有没有预充服务费,入是分店优先扣款分店服务费
//         if($store['rata_store']>0){
//             $ratamoney=$store['store_money'];
//         }
//         //判断该店是否开通技术服务费扣款和该店是否是分店，如不是分店则扣款总店服务费
//         if($store['rata_status']!=1 && !empty($store['pid'])){
//             $store=Store::where('id', $store['pid'])->first()->toarray();
//             if(empty($ratamoney)){
//                 $ratamoney=$store['store_money'];
//                 $rata_money = $store['rata_store'] * $orderdata['total_amount'] / 100;
//             }
//         }
//         if($store['with_user']>0){
//             $userdata= DB::table('users')->where('id', $store['with_user'])->first();
//             Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>$rata_money));
// //            服务费收取记录
//             $logs=array(
//                 'store_id'=>$orderdata['store_id'],
//                 'orderNo'=>$out_trade_no,
//                 'order_money'=>$orderdata['total_amount'],
//                 'rata_money'=>$rata_money,
//                 'status'=>1,
//                 'created_at'=>date("Y-m-d H:i:s",time()),
//                 'updated_at'=>date("Y-m-d H:i:s",time()),
//                 'user_id'=>$store['with_user']
//             );
//             DB::table('skill_ratastore')->insert($logs);
//             $rata_store=$userdata->settlement_money-$rata_money;
//             DB::table('users')->where('id', $userdata->id)->update(array('settlement_money'=>$rata_store));
//         }else{
//             if($store['rata_status']==1 && empty($store['pid'])){
//                 Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>round($rata_money,2)));
//                 //服务费收取记录
//                 $logs=array(
//                     'store_id'=>$orderdata['store_id'],
//                     'orderNo'=>$out_trade_no,
//                     'order_money'=>$orderdata['total_amount'],
//                     'rata_money'=>$rata_money,
//                     'status'=>1,
//                     'created_at'=>date("Y-m-d H:i:s",time()),
//                     'updated_at'=>date("Y-m-d H:i:s",time()),
//                 );
//                 DB::table('skill_ratastore')->insert($logs);
//                 $rata_store=$ratamoney-round($rata_money,2);
//                 Store::where('store_id', $store['store_id'])->update(array('store_money'=>$rata_store));
//             }else if($store['rata_status']==1 && !empty($store['pid'])){
//                 Order::where('out_trade_no', $out_trade_no)->update(array('rata_money'=>round($rata_money,2)));
//                 //服务费收取记录
//                 $logs=array(
//                     'store_id'=>$orderdata['store_id'],
//                     'orderNo'=>$out_trade_no,
//                     'order_money'=>$orderdata['total_amount'],
//                     'rata_money'=>$rata_money,
//                     'status'=>1,
//                     'created_at'=>date("Y-m-d H:i:s",time()),
//                     'updated_at'=>date("Y-m-d H:i:s",time()),
//                 );
//                 DB::table('skill_ratastore')->insert($logs);
//                 if($ratamoney<$rata_money){
//                     $store=Store::where('id', $store['id'])->first()->toarray();
//                     $ratamoney==$store['store_money'];
//                 }
//                 $rata_store=$ratamoney-round($rata_money,2);
//                 Store::where('store_id', $store['store_id'])->update(array('store_money'=>$rata_store));
//             }
//         }
        
        //计划任务扣费往期的钱
        // $where[] = ['created_at', '>=', '2021-11-08 00:00:00'];
        // $where[] = ['created_at', '<=', '2022-02-12 17:26:59'];//名爵切换前时间   202216133226775366  2022-02-12 17:29:59
        // $where[] = ['store_id', '=', '2021102815563780556'];
        // $where[] = ['pay_status', '=', 1];
        // $orders=Order::where($where)->get()->toarray();
        // foreach($orders as $key=>$val){
        //     $orderdata = Order::where('out_trade_no', $val['out_trade_no'])->first()->toarray();
        //     $store=Store::where('store_id', $orderdata['store_id'])->first()->toarray();
        //     $store=Store::where('id', $store['pid'])->first()->toarray();
        //     $ratamoney=$store['store_money'];
        //     $rata_money = $store['rata_store'] * $orderdata['total_amount'] / 100;
        //     if($val['rata_money']==0){
        //         Order::where('out_trade_no', $val['out_trade_no'])->update(array('rata_money'=>$rata_money));
        //         //服务费收取记录
        //         $logs=array(
        //             'store_id'=>$orderdata['store_id'],
        //             'orderNo'=>$val['out_trade_no'],
        //             'order_money'=>$orderdata['total_amount'],
        //             'rata_money'=>$rata_money,
        //             'status'=>1,
        //             'created_at'=>date("Y-m-d H:i:s",time()),
        //             'updated_at'=>date("Y-m-d H:i:s",time()),
        //         );
        //         DB::table('skill_ratastore')->insert($logs);
        //         $rata_store=$ratamoney-$rata_money;
        //         Store::where('store_id', $store['store_id'])->update(array('store_money'=>$rata_store));
        //     }
        // }
        // $obj = DB::table('orders');
        // $store_ids = [
        //             [
        //                 'store_id' => '202186113244626407',
        //             ]
        //         ];
        // $where13[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        // $where13[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        // $yrata_data = $obj->whereIn('store_id', $store_ids)
        //         ->where($where13)
        //         ->whereIn('pay_status', [1])
        //         ->select('rata_money');
        //         $count=$yrata_data->sum('rata_money');
        //         echo '<pre>';
        //         print_r($count);
        //         die;
        
        // $pfx=file_get_contents('https://pay.zgjindoufu.com/安徽淮风文化传媒有限公司.P12');
        // $cert_info=array();
        // $priKey=openssl_pkcs12_read($pfx,$cert_info,'97445505');
        // echo '<pre>';
        // print_r($cert_info);
        // die;
        
        // $array=array (
        //   'shop_id' => '1177055face3f3b0c4577949d66674d3',
        //   'money' => '1.1',
        //   'sign' => '3CC20F23AF02F0CFB9F5126487853C1F',
        //   'detail' => '{"receipt_id":"2021091015015465550684","goods_detail":[{"goods_name":"益达","quantity":1,"price":110,"goods_id":"6923450656150"}],"cost_price":110}',
        //   'sn' => '38545252',
        //   'body' => '阜南县外卖电子商务服务中心',
        //   'order_id' => '20210910151743040043',
        //   'auth_code' => '135206881712833792',
        // );
        // echo '<pre>';
        // print_r(json_encode($array));
        // die;
    }
    
    public function feie_nuonuo(){
        
    }
    
    public function feieyun($url,$data){
        $querystring = '';
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $querystring .= urlencode($key).'='.urlencode($val2).'&';
                    }
                } else {
                    $querystring .= urlencode($key).'='.urlencode($val).'&';
                }
            }
            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
        } else {
            $querystring = $data;
        }
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);//不抓取头部信息。只返回数据
        curl_setopt($curl, CURLOPT_TIMEOUT, (int)5000);//超时设置
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//1表示不返回bool值
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));//重点
        curl_setopt($curl, CURLOPT_POSTFIELDS, $querystring);
        $res = curl_exec($curl);
        echo '<pre>';
        print_r($res);
        die;
        return $res;
    }
    
    /**
     * 传输数据解密
     * @param string $data 编码后的字串
     * @param string $selfPrivateKey 合作方私钥
     * @return bool
     */
    public function decrypt($data, $selfPrivateKey)
    {
        $privateKey = "-----BEGIN PRIVATE KEY-----\n" .
            wordwrap($selfPrivateKey, 64, "\n", true) .
            "\n-----END PRIVATE KEY-----";

        $crypto = '';
        foreach (str_split(base64_decode($data), 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $privateKey);
            $crypto .= $decryptData;
        }
        return json_decode(iconv('GBK//IGNORE', 'UTF-8', $crypto),true);
    }
    
    //计划任务同步订单状态
    public function updata_unorder(){
        
        $obj = DB::table('orders');
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("now"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("now"))];
        $token = JWTAuth::attempt(array('phone'=>'18605581186','password'=>'WFT1603.'));
        $order=$obj->where($where)->whereIn('dk_jf', [0,1,2])->whereIn('pay_status', [2])->get();
        $order=json_decode($order,true);
        foreach($order as $key=>$val){
            file_put_contents('shuaxin.log',var_export($val['out_trade_no'],true)."\r\n",FILE_APPEND);
            $post_data=array(
                'store_id'=>$val['store_id'],
                'out_trade_no'=>$val['out_trade_no'],
                'token'=>$token
            );
            $res=$this->http_curl('https://pay.zgjindoufu.com/api/basequery/update_order', json_encode($post_data));
            Order::where('out_trade_no', $val['out_trade_no'])->update(array('dk_jf'=>$val['dk_jf']+1));
        }
    }

    //定时脚本刷新退款中订单
    public function update_refund_order()
    {
        $order = new OrderController();
        $list = DB::table('orders')->where(['pay_status'=>5])->get();
        foreach ($list as $item) {
            $result = $order->order_foreach_public([
                'out_trade_no' => $item->out_trade_no,
                'store_id' => $item->store_id,
                'ways_type' => $item->ways_type,
                'config_id' => $item->config_id,
                'created_at' => $item->created_at,
                'table' => 'orders_'.date("Ymd",strtotime($item->created_at))
            ]);
            $result = json_decode($result, true);
                $result['out_trade_no'] = $item->out_trade_no;
            if (!isset($result['status']) || $result['status'] != 1) {
                \Illuminate\Support\Facades\Log::error('update_refund_order', $result);
            }else{
                \Illuminate\Support\Facades\Log::info('update_refund_order', $result);
            }
        }

    }
    
    //翼支付退款
    public function yirefund(){
        $wftpay_return_data = [
            'institutionCode' => '3178035630163868',
            'merchantNo' => '3178031439815670',
            'outTradeNo' => 'ali_qr20210818180445295667699',
            'outRequestNo' => 'wingrerefund'.time(),
            'refundAmt' => '600',
            'requestDate' => date('Y-m-d H:i:s', time()),
            'originalTradeDate' => '2021-08-18 18:04:45',
        ];
    
        $obj = new \App\Api\Controllers\lianfu\PayController();
        $return = $obj->refund2($wftpay_return_data);
        echo '<pre>';
        print_r($return);
        die;
    }

    //跑全部预充费率
    public function ces11(){
        fastcgi_finish_request();
        $obj = DB::table('orders');
        $store_ids=['2022030721372957201','2022010721554053458','2022010702515837648','2022010619220834566','2021113014145129116'];
        $where[] = ['created_at', '>=', '2022-03-14 12:00:00'];
        $where[] = ['created_at', '<', '2022-03-21 17:00:00'];
        $order=$obj->where($where)->whereIn('store_id', $store_ids)->where('pay_status',1)->get();
//        $order = DB::table('orders')->where('out_trade_no','wxWft20220316205525216195130')->get();
        foreach($order as $key=>$val){
            file_put_contents('b.log',var_export($val->out_trade_no,true)."\r\n",FILE_APPEND);
            $rata_money = round(0.15 * $val->total_amount / 100,2);
            $rata_money3 = round(0.15 * $val->total_amount / 100,3);
            $rata_money1 = round(0.18 * $val->total_amount / 100,2);
            if($val->rata_money>$rata_money){
                $rata_money2=$rata_money1-$rata_money;
                Order::where('out_trade_no', $val->out_trade_no)->update(array('rata_money'=>$rata_money));

                DB::table('skill_ratastore')->update(array('rata_money'=>$rata_money3));

                $store=DB::table('stores')->where('store_id','2021112014242643637')->first();
                $rata_store=bcadd($store->store_money,$rata_money2,2);
                Store::where('store_id', $store->store_id)->update(array('store_money'=>$rata_store));
            }
        }
//        $rata_money=DB::table('orders')->whereIn('store_id',$store_ids)->select('rata_money')->sum('rata_money');
//        echo '<pre>';
//        print_r($rata_money);
//        die;
    }
    
    //计划任务定时清理订单表
    public function getorder(){
        // $orders = DB::table('company_day_commission')->where('settling_day','2022-06-15')->get();
        // foreach($orders as $k=>$v){
        //     $order=DB::table('company_day_commission')->where('settling_day','2022-06-15')->where('store_id',$v->store_id)->where('user_id',$v->user_id)->get();
        //     $sum=count($order);
        //     if($sum>=3){
        //         foreach ($order as $key=>$val){
        //             if($key>0){
        //                 DB::table("company_day_commission")->where(['id' => $val->id])->delete();
        //             }
        //         }
        //     }
        // }
        // $h=date('H');
        // if($h<=8 || $h<=21){
            fastcgi_finish_request();
            $where[] = ['created_at', '<=', '2023-09-30 23:59:59'];
            $orders = DB::table('orders')->where($where)->orderBy('created_at', 'asc')->select('out_trade_no')->limit(5000)->get();
            $orders=json_decode($orders,true);
            foreach($orders as $key=>$val){
                // unset($val['id']);
                // $order=DB::table('orders')->where('out_trade_no',$val['out_trade_no'])->first();
                // if(empty($order)){
                //     DB::table("orders")->insert($val);
                // }else{
                    file_put_contents('orders.log',var_export($val['out_trade_no'],true)."\r\n",FILE_APPEND);
                    DB::table('orders')->where('out_trade_no',$val['out_trade_no'])->delete();
                // }
            }
        // }
    }

    public function getdayserver(){
        //预充
        $store=DB::table('stores')->where('rata_status','1')->where('pid','0')->get();
        foreach($store as $k=>$v){
            $this->get_ratamoney($v->store_id);
            //$this->new_get_ratamoney($v->store_id);
        }
        //天街项目扣费
        $store=DB::table('stores')->where('rata_status','1')->where('pid','4377')->get();
        foreach($store as $k=>$v){
            $this->get_tianjie($v->store_id);
        }
        //服务费
        $store=DB::table('stores')->where('rata_status','2')->where('pid','0')->get();
        foreach($store as $k=>$v){
            $this->get_servermoney($v->store_id);
        }
        
        //按通道配置扣费
        $store=DB::table('stores')->where('rata_status','4')->where('pid','0')->get();
        foreach($store as $k=>$v){
            $this->get_companymoney($v->store_id);
        }
        
        //平安渠道扣费
        $store=DB::table('pingan_stores')->where('type','1')->get();
        foreach($store as $k=>$v){
            $this->get_pingancompany($v->store_id);
        }
    }
    
    public function get_tianjie($request){
        $store_id = $request;
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        $order_money = DB::table('orders')->where($where)->where('store_id',$store_id)->where('pay_status','1')->select('total_amount')->sum('total_amount');
        $rata_money=($order_money/100)*$store->rata_store;
        $rata_money=round($rata_money,2);
        $end_money=$store->store_money-$rata_money;
        $rata=array(
            'count'=>$rata_money,
            'created_at'=>strtotime(date("Y-m-d",strtotime("-1 day")).' 00:00:00'),
            'store_id'=>$store_id,
            'user_id'=>0,
            'settling_day'=>date("Y-m-d",strtotime("-1 day")),
            'before_money'=>$store->store_money,
            'end_money'=>$end_money,
            'order_count'=>$order_money
        );
        DB::table('service_day_money')->insert($rata);
        DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$end_money));
    }

    //统计店铺日使用服务费
    public function get_servermoney($request){
        $store_id = $request;
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        $user=Db::table('users')->where(['id' => '300' ])->first();
        $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
        if(empty($pstore[0]->store_id)){
            $store_ids[0]=$store_id;
        }else{
            $store_ids[0]=$store_id;
            foreach ($pstore as $k=>$v){
                $store_ids[$k+1]=$v->store_id;
            }
        }
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        $order_money = DB::table('orders')->where($where)->where('pay_status','1')->whereIn('store_id',$store_ids)->select('total_amount')->sum('total_amount');
        $rata_money=($order_money/100)*$store->rata_store;
        $rata_money=round($rata_money,2);
        $end_money=$user->settlement_money-$rata_money;
        $rata=array(
            'count'=>$rata_money,
            'created_at'=>strtotime(date("Y-m-d",strtotime("-1 day")).' 00:00:00'),
            'store_id'=>$store_id,
            'user_id'=>300,
            'settling_day'=>date("Y-m-d",strtotime("-1 day")),
            'before_money'=>$user->settlement_money,
            'end_money'=>$end_money,
            'order_count'=>$order_money
        );
        DB::table('service_day_money')->insert($rata);
        DB::table('users')->where('id','300')->update(array('settlement_money'=>$end_money));
    }
    
      //预充扣费
    public function new_get_ratamoney($request,$settling_day){
        $log_path = storage_path()."/logs/". 'service_bill_log_add'.date('Ymd').".log";
        error_log(date('Y-m-d H:i:s')." 【新预充扣费开始】："."\n\n", 3, $log_path);
        DB::beginTransaction();
        try {
            if (DB::table('service_day_money')->where(['store_id' => $request, 'settling_day' => $settling_day])->first()) {
                return 'al success';
            }
            
            $store_id = $request;
            $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
            $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
            if(empty($pstore[0]->store_id)){
                $store_ids[0]=$store_id;
            }else{
                $store_ids[0]=$store_id;
                foreach ($pstore as $k=>$v){
                    $store_ids[$k+1]=$v->store_id;
                }
            }
            $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime($settling_day))];
            $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime($settling_day))];
            $order_money = DB::table('skill_ratastore')->where($where)->whereIn('store_id',$store_ids)
            ->select('order_money')->sum('order_money');
            $rata_money=($order_money/100)*$store->rata_store;
            $rata_money=round($rata_money,2);
            $end_money=$store->store_money-$rata_money;
            $rata=array(
                'count'=>$rata_money,
                'created_at'=>strtotime($settling_day.' 00:00:00'),
                'store_id'=>$store_id,
                'user_id'=>0,
                'settling_day'=>$settling_day,
                'before_money'=>$store->store_money,
                'end_money'=>$end_money,
                'order_count'=>$order_money
            );
            DB::table('service_day_money')->insert($rata);
            DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$end_money));
            DB::commit();
            return 'success';
        } catch (\Exception $e) {
            DB::rollBack();
            error_log(date('Y-m-d H:i:s')." 【新预充扣费异常】：".$e->getMessage().'_'.$e->getLine()."\n\n", 3, $log_path);
            return $e->getMessage().'_'.$e->getLine();
        }
    }
    
    public function addServiceBill(Request $request){
        $settling_day = date("Y-m-d",strtotime("-1 day"));
        if($request->has('settling_day') && $request['settling_day']){
            $settling_day = $request['settling_day'];
        }
        $store_obj = DB::table('stores')->where('rata_status','1')->where('pid','0')->select('store_id');
        if($request->has('store_id') && $request['store_id']){
            $store_obj->where('store_id',trim($request['store_id']));
        }
        $bill_store = DB::table('service_day_money')->where(['settling_day' => $settling_day])->pluck('store_id')->toArray();
        $store_obj->whereNotIn('store_id',$bill_store);
        //预充
        $store = $store_obj->orderBy('id','ASC')->limit(20)->get();
        //return $store;
        $res = [];
        foreach($store as $k=>$v){
            $res[] = $this->new_get_ratamoney(trim($v->store_id),$settling_day);
        }
        return $res;
    }
    
    public function addServiceBill1(Request $request){
        $settling_day = date("Y-m-d",strtotime("-1 day"));
        if($request->has('settling_day') && $request['settling_day']){
            $settling_day = $request['settling_day'];
        }
        $store_obj = DB::table('stores')->where('rata_status','1')->where('pid','0')->select('store_id');
        if($request->has('store_id') && $request['store_id']){
            $store_obj->where('store_id',trim($request['store_id']));
        }
        $bill_store = DB::table('service_bill_log')->where(['settling_day' => $settling_day])->pluck('store_id')->toArray();
        $store_obj->whereNotIn('store_id',$bill_store);
        //预充
        $store = $store_obj->orderBy('id','ASC')->limit(20)->get();
        $res = [];
        foreach($store as $k=>$v){
            $res[] = $this->new_get_ratamoney(trim($v->store_id),$settling_day);
        }
        return $res;
    }
    
    
    //预充扣费
    public function new_get_ratamoney1($request,$settling_day){
        $log_path = storage_path()."/logs/". 'service_bill_log_add'.date('Ymd').".log";
        error_log(date('Y-m-d H:i:s')." 【新预充扣费开始】："."\n\n", 3, $log_path);
        DB::beginTransaction();
        try {
            $onlyno = $request.'_'.$settling_day;
            if (DB::table('service_bill_log')->where(['onlyno' => $onlyno])->first()) {
                return 'success';
            }
            $store_id = $request;
            $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
            $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
            if(empty($pstore[0]->store_id)){
                $store_ids[0]=$store_id;
            }else{
                $store_ids[0]=$store_id;
                foreach ($pstore as $k=>$v){
                    $store_ids[$k+1]=$v->store_id;
                }
            }
            $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime($settling_day))];
            $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime($settling_day))];
            $order_res = DB::table('orders')
                        ->where($where)
                        ->whereIn('status',[1,6,'TRADE_SUCCESS','SUCCESS'])
                        ->whereIn('store_id',$store_ids)
                        ->selectRaw('sum(total_amount) as total_amount,sum(refund_amount) as refund_amount')
                        ->first();
            $total_fee = bcmul($order_res->total_amount,100) - bcmul($order_res->refund_amount,100);
            $rata_money = round(bcdiv(bcmul($store->rata_store,100)*$total_fee,10000,1));
            $before_money = bcmul($store->store_money,100);
            $end_money=$before_money-$rata_money;
            $rata=array(
                'store_id'=>trim($store_id),
                'total_fee'=>$total_fee,
                'service_fee'=>$rata_money,
                'before_money'=>$before_money,
                'end_money'=>$end_money,
                'settling_day'=>$settling_day,
                'onlyno'=>$onlyno,
                'created_at'=>date("Y-m-d H:i:s"),
            );
            DB::table('service_bill_log')->insert($rata);
            DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>bcdiv($end_money,100,2)));
            DB::commit();
            error_log(date('Y-m-d H:i:s')." 【新预充扣费结束】："."\n\n", 3, $log_path);
            return 'success';
        } catch (\Exception $e) {
            DB::rollBack();
            error_log(date('Y-m-d H:i:s')." 【新预充扣费异常】：".$e->getMessage().'_'.$e->getLine()."\n\n", 3, $log_path);
            return $e->getMessage().'_'.$e->getLine();
        }
    }
    
    //预充扣费
    public function get_ratamoney($request){
        
        if (DB::table('service_day_money')->where(['store_id' => $request, 'settling_day' => date("Y-m-d",strtotime("-1 day"))])->first()) {
            return ;
        }
        
        $store_id = $request;
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
        if(empty($pstore[0]->store_id)){
            $store_ids[0]=$store_id;
        }else{
            $store_ids[0]=$store_id;
            foreach ($pstore as $k=>$v){
                $store_ids[$k+1]=$v->store_id;
            }
        }
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        
        
        //剔除退款
        $where[] = ['status', '=', 1];
        //剔除退款
        
        $order_money = DB::table('skill_ratastore')->where($where)->whereIn('store_id',$store_ids)->select('order_money')->sum('order_money');
        $rata_money=($order_money/100)*$store->rata_store;
        $rata_money=round($rata_money,2);
        $end_money=$store->store_money-$rata_money;
        $rata=array(
            'count'=>$rata_money,
            'created_at'=>strtotime(date("Y-m-d",strtotime("-1 day")).' 00:00:00'),
            'store_id'=>$store_id,
            'user_id'=>0,
            'settling_day'=>date("Y-m-d",strtotime("-1 day")),
            'before_money'=>$store->store_money,
            'end_money'=>$end_money,
            'order_count'=>$order_money
        );
        DB::table('service_day_money')->insert($rata);
        DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$end_money));
    }
    //预充扣费
    public function get_companymoney($request){
        $store_id = $request;
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
        if(empty($pstore[0]->store_id)){
            $store_ids[0]=$store_id;
        }else{
            $store_ids[0]=$store_id;
            foreach ($pstore as $k=>$v){
                $store_ids[$k+1]=$v->store_id;
            }
        }
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        $where['company'] ='wftpay';
        $where['pay_status'] ='1';
        $order_money = DB::table('orders')->where($where)->whereIn('store_id',$store_ids)->select('total_amount')->sum('total_amount');
        $rata_money=($order_money/100)*$store->rata_store;
        $rata_money=round($rata_money,2);
        $end_money=$store->store_money-$rata_money;
        $rata=array(
            'count'=>$rata_money,
            'created_at'=>strtotime(date("Y-m-d",strtotime("-1 day")).' 00:00:00'),
            'store_id'=>$store_id,
            'user_id'=>0,
            'settling_day'=>date("Y-m-d",strtotime("-1 day")),
            'before_money'=>$store->store_money,
            'end_money'=>$end_money,
            'order_count'=>$order_money
        );
        DB::table('service_day_money')->insert($rata);
        DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$end_money));
    }
    
    //平安扣费
    public function get_pingancompany($request){
        $store_id = $request;
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
        $user=Db::table('users')->where(['id' => '347' ])->first();
        if(empty($pstore[0]->store_id)){
            $store_ids[0]=$store_id;
        }else{
            $store_ids[0]=$store_id;
            foreach ($pstore as $k=>$v){
                $store_ids[$k+1]=$v->store_id;
            }
        }
        $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("-1 day"))];
        $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("-1 day"))];
        
        $where['company'] ='pingan';
        $where['pay_status'] ='1';
        $order_money = DB::table('orders')->where($where)->whereIn('store_id',$store_ids)->select('total_amount')->sum('total_amount');
        $rata_money=($order_money/100)*0.01;
        $rata_money=round($rata_money,2);
        $end_money=$user->settlement_money-$rata_money;
        $rata=array(
            'count'=>$rata_money,
            'created_at'=>strtotime(date("Y-m-d",strtotime("-1 day")).' 00:00:00'),
            'store_id'=>$store_id,
            'user_id'=>347,
            'settling_day'=>date("Y-m-d",strtotime("-1 day")),
            'before_money'=>$store->store_money,
            'end_money'=>$end_money,
            'order_count'=>$order_money
        );
        DB::table('service_day_money')->insert($rata);
        DB::table('users')->where('id','347')->update(array('settlement_money'=>$end_money));
    }
    
    public function cefenrun(){
        session_start();
        fastcgi_finish_request();
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $settling_day=$date_time;
        $table='orders_' . date("Ymd", strtotime("-1 day"));
        $time=strtotime($settling_day)+100;
        $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
        $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
        
        $company_config=DB::table('company_config')->get();
        //4：预充 3：通道扣费 2：代扣 1：服务费
        foreach($company_config as $k=>$v){
            file_put_contents('ceshif.log',var_export($v->id,true)."\r\n",FILE_APPEND);
            $user_id = DB::table('stores')->where([ 'store_id' => $v->store_id ])->value('user_id');
            unset($_SESSION['users']);
            $users = $this->recursion1($user_id);
            $users = json_decode($users, true);
            $users = array_reverse($users);
            
            // $users=unserialize($v->users_rate);
            unset($store);
            unset($p_stores);
            unset($store_ids);
            $store = DB::table('stores')->where('store_id', $v->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
            
            $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
            if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $store->store_id;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v->company)->where('status', 1)->select('company')->distinct()->first();
                    if(empty($pay_ways)){
                        $store_ids[] = $v1['store_id'];
                    }
                }
            }else{
                $store_ids[0] = $store->store_id;
            }
            $total_amount=DB::table($table)->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            $total_num=DB::table($table)->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
            $refund_amount=DB::table($table)->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 6)->select('refund_amount')->sum('refund_amount');
            $total_amount1=$total_amount;
            $total_amount=$total_amount-$refund_amount;
            if($v->model==4){
                foreach($users as $key=>$val){
                    $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                    $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                    $basic_money=round(($total_amount/100)*$user_rates->yu_rate,2);
                    $commission_money=$fee_amount-$basic_money;
                    
                    if($commission_money<0){
                        $commission_money='0.00';
                    }
                    
                    if($user_rates->yu_rate==$v->configure_channel_fee){
                        $commission_money='0.00';
                        $fee_amount='0.00';
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$v->store_id,
                        'total_amount'=>$total_amount1,
                        'fee_amount'=>$fee_amount,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>0,
                        'created_at'=>$time,
                        'total_num'=>$total_num,
                        'refund_amount'=>$refund_amount,
                        'user_id'=>$val['id']
                    );
                    DB::table('company_day_commission')->insert($arr);
                }
            }else if($v->model==3){
                foreach($users as $key=>$val){
                    $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                    if($v->company=='vbill'){
                        $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                    }else{
                        $fee_amount=DB::table($table)->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 1)->select('fee_amount')->sum('fee_amount');
                    }
                    $basic_money=round(($total_amount/100)*$user_rates->rate,2);
                    $commission_money=$fee_amount-$basic_money;
                    if($commission_money<0){
                        $commission_money='0.00';
                    }
                    if($user_rates->rate==$v->configure_channel_fee){
                        $commission_money='0.00';
                        $fee_amount='0.00';
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$v->store_id,
                        'total_amount'=>$total_amount1,
                        'fee_amount'=>$fee_amount,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>0,
                        'created_at'=>$time,
                        'total_num'=>$total_num,
                        'refund_amount'=>$refund_amount,
                        'user_id'=>$val['id']
                    );
                    DB::table('company_day_commission')->insert($arr);
                }
            }else if($v->model==2){
                foreach($users as $key=>$val){
                    $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                    $fee_amount=DB::table($table)->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 1)->select('fee_amount')->sum('fee_amount');
                    $basic_money=round(($total_amount/100)*$user_rates->era_rate,2);
                    $commission_money=$fee_amount-$basic_money;
                    if($commission_money<0){
                        $commission_money='0.00';
                    }
                    if($user_rates->era_rate==$v->configure_channel_fee){
                        $commission_money='0.00';
                        $fee_amount='0.00';
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$v->store_id,
                        'total_amount'=>$total_amount1,
                        'fee_amount'=>$fee_amount,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>0,
                        'created_at'=>$time,
                        'total_num'=>$total_num,
                        'refund_amount'=>$refund_amount,
                        'user_id'=>$val['id']
                    );
                    DB::table('company_day_commission')->insert($arr);
                }
            }else if($v->model==1){
                
                foreach($users as $key=>$val){
                    $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                    $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                    $basic_money=round(($total_amount/100)*$user_rates->server_rate,2);
                    $commission_money=$fee_amount-$basic_money;
                    if($commission_money<0){
                        $commission_money='0.00';
                    }
                    if($user_rates->server_rate<=$v->configure_channel_fee){
                        $commission_money='0.00';
                        $fee_amount='0.00';
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$v->store_id,
                        'total_amount'=>$total_amount1,
                        'fee_amount'=>$fee_amount,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>0,
                        'created_at'=>$time,
                        'total_num'=>$total_num,
                        'refund_amount'=>$refund_amount,
                        'user_id'=>$val['id']
                    );
                    DB::table('company_day_commission')->insert($arr);
                }
            }
        }
        unset($users);
    }
    
    // /**
    //  * 递归
    //  * 2022/09/06 16:07
    //  */
    public function recursion1($user_id,$i = 0){
        $user = DB::table('users')->where([ 'id' => $user_id ])->select('id', 'name', 'pid')->get();
        $user = json_decode($user,true);
        if( $user[0]['pid'] !== '0'){
            $_SESSION['users'][$i] = $user[0];
            $i++;
            $this->recursion1($user[0]['pid'],$i);
        }else{
            $_SESSION['users'][$i] = $user[0];
        }
        return json_encode((object)$_SESSION['users']);
    }
    
    //统计店铺数据
    public function store_count(){
        fastcgi_finish_request();
        $table='orders_' . date("Ymd", strtotime("-1 day"));
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $stores=DB::table('stores')->where('id','<=','4000')->get();
        $stores=json_decode($stores,true);
        foreach($stores as $k=>$v){
            $store_id=$v['store_id'];
            file_put_contents('storecount2.log',var_export($store_id,true)."\r\n",FILE_APPEND);
            $store=DB::table('stores')->where(array('store_id'=>$store_id))->first();
            if($store->pid>0){
                $upstore=DB::table('stores')->where(array('id'=>$store->pid))->first();
            }
            $settling_day=$date_time;
            $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
            $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
            $time=strtotime($settling_day)+600;
            //总收款
            $total_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            
            //总手续费
            $fee_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
            
            //总退款
            $refund_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
            
            //总收款笔
            $total_num=count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->get());
            
            //总退款笔数
            $refund_num=count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->get());
            
            //微信收款总额
            $weixin_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->sum('total_amount');
            
            //微信收款笔数
            $weixin_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->get());
            
            //支付宝收款金额
            $alipay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->sum('total_amount');
            
            //支付宝收款笔数
            $alipay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->get());
            
            // 云闪付收款金额
            $unionpay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->sum('total_amount');
            
            // 云闪付收款笔数
            $unionpay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->get());
            
             // 翼支付收款金额
            $Bestpay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            
            // 翼支付收款笔数
            $Bestpay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->get());
            $arr=array(
                'store_amount'=>$total_amount-$refund_amount,
                'refund_amount'=>$refund_amount,
                'fee_amount'=>$fee_amount,
                'store_order_count'=>$total_num,
                'refund_order_num'=>$refund_num,
                'store_id'=> $store_id,
                'sub_storeid'=>$store->pid==0 ? 0 :$upstore->store_id,
                'settling_day'=>$settling_day,
                'weixin_amount'=>$weixin_total_amount,
                'weixin_num'=>$weixin_total_num,
                'alipay_amount'=>$alipay_total_amount,
                'alipay_num'=>$alipay_total_num,
                'unionpay_amount'=>$unionpay_total_amount,
                'unionpay_num'=>$unionpay_total_num,
                'bestpay_amount'=>$Bestpay_total_amount,
                'bestpay_num'=>$Bestpay_total_num,
                'created_at'=>$time
            );

            DB::table('stores_day_count')->insert($arr);
            $where1['store_id']=$store_id;
            $merchant_stores = DB::table('merchant_stores')->where($where1)->select()->get();
            $merchant_stores=json_decode($merchant_stores,true);
            foreach($merchant_stores as $key=>$val){
                $merchant_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->sum('total_amount');
                $merchant_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->get());
                $mer=array(
                    'store_id'=>$store_id,
                    'merchant_id'=>$val['merchant_id'],
                    'merchant_money'=>$merchant_amount,
                    'merchant_num'=>$merchant_num,
                    'created_at'=>$time,
                    'settling_day'=>$settling_day,
                );
                DB::table('stores_cash_count')->insert($mer);
            }
        }
    }
    
    //统计店铺数据
    public function store_count1(){
        fastcgi_finish_request();
        $table='orders_' . date("Ymd", strtotime("-1 day"));
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $stores=DB::table('stores')->where('id','>','4000')->get();
        $stores=json_decode($stores,true);
        foreach($stores as $k=>$v){
            $store_id=$v['store_id'];
            file_put_contents('storecount2.log',var_export($store_id,true)."\r\n",FILE_APPEND);
            $store=DB::table('stores')->where(array('store_id'=>$store_id))->first();
            if($store->pid>0){
                $upstore=DB::table('stores')->where(array('id'=>$store->pid))->first();
            }
            $settling_day=$date_time;
            $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
            $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
            $time=strtotime($settling_day)+600;
            //总收款
            $total_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            
            //总手续费
            $fee_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
            
            //总退款
            $refund_amount=DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
            
            //总收款笔
            $total_num=count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->get());
            
            //总退款笔数
            $refund_num=count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->get());
            
            //微信收款总额
            $weixin_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->sum('total_amount');
            
            //微信收款笔数
            $weixin_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->get());
            
            //支付宝收款金额
            $alipay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->sum('total_amount');
            
            //支付宝收款笔数
            $alipay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->get());
            
            // 云闪付收款金额
            $unionpay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->sum('total_amount');
            
            // 云闪付收款笔数
            $unionpay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->get());
            
             // 翼支付收款金额
            $Bestpay_total_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
            
            // 翼支付收款笔数
            $Bestpay_total_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->get());
            $arr=array(
                'store_amount'=>$total_amount-$refund_amount,
                'refund_amount'=>$refund_amount,
                'fee_amount'=>$fee_amount,
                'store_order_count'=>$total_num,
                'refund_order_num'=>$refund_num,
                'store_id'=> $store_id,
                'sub_storeid'=>$store->pid==0 ? 0 :$upstore->store_id,
                'settling_day'=>$settling_day,
                'weixin_amount'=>$weixin_total_amount,
                'weixin_num'=>$weixin_total_num,
                'alipay_amount'=>$alipay_total_amount,
                'alipay_num'=>$alipay_total_num,
                'unionpay_amount'=>$unionpay_total_amount,
                'unionpay_num'=>$unionpay_total_num,
                'bestpay_amount'=>$Bestpay_total_amount,
                'bestpay_num'=>$Bestpay_total_num,
                'created_at'=>$time
            );

            DB::table('stores_day_count')->insert($arr);
            $where1['store_id']=$store_id;
            $merchant_stores = DB::table('merchant_stores')->where($where1)->select()->get();
            $merchant_stores=json_decode($merchant_stores,true);
            foreach($merchant_stores as $key=>$val){
                $merchant_amount = DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->sum('total_amount');
                $merchant_num = count(DB::table($table)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->get());
                $mer=array(
                    'store_id'=>$store_id,
                    'merchant_id'=>$val['merchant_id'],
                    'merchant_money'=>$merchant_amount,
                    'merchant_num'=>$merchant_num,
                    'created_at'=>$time,
                    'settling_day'=>$settling_day,
                );
                DB::table('stores_cash_count')->insert($mer);
            }
        }
    }
    
    public function getfather($id){
        $user=DB::table('users')->where('id', $id)->select('id','level','pid')->first();
        $arr[0]['id']=$user->id;
        $arr[0]['level']=$user->level;
        $user_id=$user->id;
        $i=1;
//        $user=json_encode($user,true);
        while ($user->pid!=0){
            $user=DB::table('users')->where('id', $user->pid)->select('id','level','pid')->first();
            $arr[$i]['id']=$user->id;
            $arr[$i]['level']=$user->level;
            $user_id=$user->id;
            $i++;
        }
        unset($i);
        return $arr;
    }


    public function company_commission(){
        fastcgi_finish_request();
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $settling_day=$date_time;
        $time=strtotime($settling_day)+100;
        $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
        $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
        $stores=DB::table('stores')->get();
        $stores=json_decode($stores,true);
        foreach($stores as $k=>$v){
            $store_id=$v['store_id'];
            // $store_id='2022030514583687006';
            file_put_contents('b133.log',var_export($store_id,true)."\r\n",FILE_APPEND);
            $store=DB::table('stores')->where('store_id',$store_id)->first();
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->where('status', 1)->select('company')->distinct()->get()->toArray();
            if(empty($pay_ways)&& !empty($store->pid)){
                $p_store=DB::table('stores')->where('id',$store->pid)->first();
                $p_pay_ways=DB::table('store_pay_ways')->where('store_id', $p_store->store_id)->where('status', 1)->select('company','rate')->distinct()->get()->toArray();
                //预充值扣费通道
                $rata_company=['pingan','nongjin','wftpay'];
                foreach($p_pay_ways as $k=>$v){
                    if($p_store->rata_status==1 && in_array($v->company,$rata_company)){
                        //通道交易额
                        $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                        //该通道服务费扣取总额
                        if($store->rata_store=='0.00'){
                            $rata_money=($total_amount/100)*$p_store->rata_store;
                        }else{
                            $rata_money=($total_amount/100)*$store->rata_store;
                        }
                        $rata_money=round($rata_money,2);
                        $total_num=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->count('total_amount');
                        $refund_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
                        $user_ids = $this->getfather($store->user_id);
                        foreach($user_ids as $k1=>$v1){
                            $user_pay_ways=DB::table('server_rates')->where('user_id', $v1['id'])->where('company', $v->company)->select('rate')->distinct()->first();
                            if(empty($user_pay_ways->rate)){
                                //基本费率扣取额
                                $basic_money=round(($total_amount/100)*0.00,2);
                            }else{
                                //基本费率扣取额
                                $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                            }
                            //服务费扣取总额-基本费率扣取额=该通道返佣金额
                            if($rata_money>$basic_money){
                                $commission_money=round($rata_money-$basic_money,2);
                            }else{
                                $commission_money=0.00;
                                $basic_money=$rata_money;
                            }
                            $arr=array(
                                'company'=>$v->company,
                                'store_id'=>$store_id,
                                'total_amount'=>$total_amount,
                                'fee_amount'=>$rata_money,
                                'basic_money'=>$basic_money,
                                'commission_money'=> $commission_money,
                                'settling_day'=>$settling_day,
                                'is_rate'=>1,
                                'created_at'=>$time,
                                'total_num'=>$total_num,
                                'refund_amount'=>$refund_amount,
                                'user_id'=>$v1['id']
                            );

                            DB::table('company_day_commission')->insert($arr);
                        }
                    }else{
                        $user_pay_ways=DB::table('user_rates')->where('user_id', $p_store->user_id)->where('company', $v->company)->select('rate')->distinct()->first();
                        $total_amount=DB::table('orders')->where('store_id', $store->store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                        $total_num=DB::table('orders')->where('store_id', $store->store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->count('total_amount');
                        $refund_amount=DB::table('orders')->where('store_id', $store->store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
                        //通道总手续费
                        $store_pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->where('company',$v->company)->first();
                        if(empty($store_pay_ways->rate)){
                            $store_pay_ways=DB::table('store_pay_ways')->where('store_id', $p_store->store_id)->where('company',$v->company)->first();
                        }
                        $fee_amount=round(($total_amount/100)*$store_pay_ways->rate,2);
                        $user_ids = $this->getfather($store->user_id);
                        foreach($user_ids as $k1=>$v1){
                            $user_pay_ways=DB::table('user_rates')->where('user_id', $v1['id'])->where('company', $v->company)->select('rate')->distinct()->first();
                            //基本费率扣取额
                            $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                            if($fee_amount>$basic_money) {
                                $commission_money = round($fee_amount - $basic_money, 2);
                            }else{
                                $commission_money=0.00;
                                $basic_money=$fee_amount;
                            }
                            $arr=array(
                                'company'=>$v->company,
                                'store_id'=>$store_id,
                                'total_amount'=>$total_amount,
                                'fee_amount'=>$fee_amount,
                                'basic_money'=>$basic_money,
                                'commission_money'=> $commission_money,
                                'settling_day'=>$settling_day,
                                'is_rate'=>0,
                                'created_at'=>$time,
                                'total_num'=>$total_num,
                                'refund_amount'=>$refund_amount,
                                'user_id'=>$v1['id']
                            );
                            DB::table('company_day_commission')->insert($arr);
                        }
                    }
                }
            }else{
                //预充值扣费通道
                $rata_company=['pingan','nongjin','wftpay'];
                if(!empty($pay_ways)){
                    foreach ($pay_ways as $k=>$v){
                        if($store->rata_status==1 && in_array($v->company,$rata_company)){
                            //通道交易额
                            $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                            $total_num=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->count('total_amount');
                            $refund_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
                            //该通道服务费扣取总额
                            $rata_money=($total_amount/100)*$store->rata_store;
                            $user_ids = $this->getfather($store->user_id);
                            foreach($user_ids as $k1=>$v1){
                                $user_pay_ways=DB::table('server_rates')->where('user_id', $v1['id'])->where('company', $v->company)->select('rate')->distinct()->first();
                                //基本费率扣取额
                                $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                                //服务费扣取总额-基本费率扣取额=该通道返佣金额
                                if($rata_money>$basic_money){
                                    $commission_money=round($rata_money-$basic_money,2);
                                }else{
                                    $commission_money=0.00;
                                    $basic_money=$rata_money;
                                }
                                $arr=array(
                                    'company'=>$v->company,
                                    'store_id'=>$store_id,
                                    'total_amount'=>$total_amount,
                                    'fee_amount'=>$rata_money,
                                    'basic_money'=>$basic_money,
                                    'commission_money'=> $commission_money,
                                    'settling_day'=>$settling_day,
                                    'is_rate'=>1,
                                    'created_at'=>$time,
                                    'total_num'=>$total_num,
                                    'refund_amount'=>$refund_amount,
                                    'user_id'=>$v1['id']
                                );

                                DB::table('company_day_commission')->insert($arr);
                            }
                        }else{
                            //通道交易额
                            $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                            $total_num=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->count('total_amount');
                            $refund_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
                            //通道总手续费

                            $store_pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->where('company',$v->company)->first();
                            $fee_amount=round(($total_amount/100)*$store_pay_ways->rate,2);
                            $user_ids = $this->getfather($store->user_id);
                            foreach($user_ids as $k1=>$v1){
                                $user_pay_ways=DB::table('user_rates')->where('user_id', $v1['id'])->where('company', $v->company)->select('rate')->distinct()->first();
                                //基本费率扣取额
                                $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                                //服务费扣取总额-基本费率扣取额=该通道返佣金额
                                if($fee_amount>$basic_money){
                                    $commission_money=round($fee_amount-$basic_money,2);
                                }else{
                                    $commission_money=0.00;
                                    $basic_money=$fee_amount;
                                }
                                $arr=array(
                                    'company'=>$v->company,
                                    'store_id'=>$store_id,
                                    'total_amount'=>$total_amount,
                                    'fee_amount'=>$fee_amount,
                                    'basic_money'=>$basic_money,
                                    'commission_money'=> $commission_money,
                                    'settling_day'=>$settling_day,
                                    'is_rate'=>0,
                                    'created_at'=>$time,
                                    'total_num'=>$total_num,
                                    'refund_amount'=>$refund_amount,
                                    'user_id'=>$v1['id']
                                );
                                DB::table('company_day_commission')->insert($arr);
                            }
                        }
                    }
                }
            }
        }
    }
    //测试佣金
    public function cscompany_commission(){
        $date_time=date("Y-m-d",strtotime("-19 day"));
        $settling_day=$date_time;
        $time=strtotime($settling_day)+100;
        $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
        $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
        $store_id='202162514053427744';
        $store=DB::table('stores')->where('store_id',$store_id)->first();
        $pay_ways=DB::table('store_pay_ways')->where('store_id', $store_id)->where('status', 1)->select('company')->distinct()->get()->toArray();
        if(empty($pay_ways)&& !empty($store->pid)){
            $p_store=DB::table('stores')->where('id',$store->pid)->first();
            $p_pay_ways=DB::table('store_pay_ways')->where('store_id', $p_store->store_id)->where('status', 1)->select('company','rate')->distinct()->get()->toArray();
            //预充值扣费通道
            $rata_company=['pingan','nongjin','wftpay'];
            foreach($p_pay_ways as $k=>$v){
                if($p_store->rata_status==1 && in_array($v->company,$rata_company)){
                    //通道交易额
                    $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                    //该通道服务费扣取总额
                    $rata_money=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('rata_money')->sum('rata_money');
                    //基本费率扣取额
                    $basic_money=round(($total_amount/100)*$p_store->basic_rata,2);
                    //服务费扣取总额-基本费率扣取额=该通道返佣金额
                    if($rata_money>$basic_money){
                        $commission_money=round($rata_money-$basic_money,2);
                    }else{
                        $commission_money=0.00;
                        $basic_money=$rata_money;
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$store_id,
                        'total_amount'=>$total_amount,
                        'fee_amount'=>$rata_money,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>1,
                        'created_at'=>$time
                    );

                    DB::table('company_day_commission')->insert($arr);
                }else{
                    $user_pay_ways=DB::table('user_rates')->where('user_id', $p_store->user_id)->where('company', $v->company)->select('rate')->distinct()->first();
                    $total_amount=DB::table('orders')->where('store_id', $store->store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                    //通道总手续费
                    $fee_amount=DB::table('orders')->where('store_id', $store->store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('fee_amount')->sum('fee_amount');
                    //基本费率扣取额
                    $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                    if($fee_amount>$basic_money) {
                        $commission_money = round($fee_amount - $basic_money, 2);
                    }else{
                        $commission_money=0.00;
                        $basic_money=$fee_amount;
                    }
                    $arr=array(
                        'company'=>$v->company,
                        'store_id'=>$store_id,
                        'total_amount'=>$total_amount,
                        'fee_amount'=>$fee_amount,
                        'basic_money'=>$basic_money,
                        'commission_money'=> $commission_money,
                        'settling_day'=>$settling_day,
                        'is_rate'=>0,
                        'created_at'=>$time
                    );
                    DB::table('company_day_commission')->insert($arr);
                }
            }
        }else{
            //预充值扣费通道
            $rata_company=['pingan','nongjin','wftpay'];
            if(!empty($pay_ways)){
                foreach ($pay_ways as $k=>$v){
                    if($store->rata_status==1 && in_array($v->company,$rata_company)){
                        //通道交易额
                        $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                        //该通道服务费扣取总额
                        $rata_money=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('rata_money')->sum('rata_money');
                        //基本费率扣取额
                        $basic_money=round(($total_amount/100)*$store->basic_rata,2);
                        //服务费扣取总额-基本费率扣取额=该通道返佣金额
                        if($rata_money>$basic_money){
                            $commission_money=round($rata_money-$basic_money,2);
                        }else{
                            $commission_money=0.00;
                            $basic_money=$rata_money;
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$store_id,
                            'total_amount'=>$total_amount,
                            'fee_amount'=>$rata_money,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>1,
                            'created_at'=>$time
                        );

                        DB::table('company_day_commission')->insert($arr);
                    }else{
                        $user_pay_ways=DB::table('user_rates')->where('user_id', $store->user_id)->where('company', $v->company)->select('rate')->distinct()->first();
                        //通道交易额
                        $total_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('total_amount')->sum('total_amount');
                        //通道总手续费
                        $fee_amount=DB::table('orders')->where('store_id', $store_id)->where('company',$v->company)->where($where)->whereIn('pay_status', [1,6])->select('fee_amount')->sum('fee_amount');
                        //基本费率扣取额
                        $basic_money=round(($total_amount/100)*$user_pay_ways->rate,2);
                        //服务费扣取总额-基本费率扣取额=该通道返佣金额
                        if($fee_amount>$basic_money){
                            $commission_money=round($fee_amount-$basic_money,2);
                        }else{
                            $commission_money=0.00;
                            $basic_money=$fee_amount;
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$store_id,
                            'total_amount'=>$total_amount,
                            'fee_amount'=>$fee_amount,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>0,
                            'created_at'=>$time
                        );

                        DB::table('company_day_commission')->insert($arr);
                    }
                }
            }
        }
    }
    
    public function cs(){
        $stores=DB::table('stores')->select('store_id')->get();
        foreach ($stores as $k=>$v){
            $pay_ways=DB::table('store_pay_ways')->where('store_id', $v->store_id)->select('company')->distinct()->get();
            foreach($pay_ways as $key=>$val){
                $company_config=DB::table('company_config')->where('store_id', $v->store_id)->where('company', $val->company)->first();
                if(empty($company_config)){
                    $text='门店id：'.$v->store_id .' 未配置通道为：'.$val->company;
                    file_put_contents('config.log',var_export($text,true)."\r\n",FILE_APPEND);
                }
            }
        }
        echo 44;
    }
    //根据商户流水对商户进行排序
    public function editstore_sort(){
        fastcgi_finish_request();
        $where[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
        $where[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
//        $stores=DB::table('stores_day_count')->where($where)->where('sub_storeid',0)->select('store_amount','store_id')->orderBy('store_amount','desc')->get();
//        echo '<pre>';
//        print_r($stores);
//        die;
        $store_ids=DB::table('stores')->where('pid', '=',0)->select('store_id','id')->get();
        $store_ids=json_decode($store_ids,true);
        foreach($store_ids as $k=>$v){
            $p_stores=DB::table('stores')->where('pid',$v['id'])->select('store_id')->get();
            if(!empty($p_stores[0]->store_id)){
                $p_store_data[0]=$v['store_id'];
                $p_stores=json_decode($p_stores,true);
                foreach($p_stores as $k1=>$v1){
                    $p_store_data[]=$v1['store_id'];
                }
                $store_ids[$k]['total_amount']=DB::table('stores_day_count')->whereIn('store_id', $p_store_data)->where($where)->select('store_amount')->sum('store_amount');
                unset($p_store_data);
            }else{
                $store_ids[$k]['total_amount']=DB::table('stores_day_count')->where('store_id', $v['store_id'])->where($where)->select('store_amount')->sum('store_amount');
            }
        }
        $sort=array_column($store_ids,'total_amount');
        array_multisort($sort, SORT_ASC, $store_ids);
        foreach ($store_ids as $key=>$val){
            Store::where('store_id', $val['store_id'])->update(array('sort'=>$key));
        }
    }
    //语音设备测试
    public function CG02(){
        $out_order_id='wx_qr20220505144113882906688';
        $params=array(
            'appId'=>'ZF441',
            'timestamp'=>time().'000',
            'requestId'=>$out_order_id,
            'userCode'=>'ZF441',
        );

        $tokenString='';
        ksort($params);
        foreach ($params as $k=>$v){
            $tokenString.=$k.$v;
        }
        $token=strtoupper(md5($tokenString.'2022bsjZF441EYN'));

        $params['token']=$token;
        $params['devName']='ZF4414GW00002';
        $params['money']='1';
        $params['broadCastType']=2;
        $params_string=$this->allin_Params($params);
        $url='https://ioe.car900.com/v1/openApi/dev/controlDevice.json?'.$params_string;
        $res=$this->curl_merch($url,'GET',json_encode($params),array('Content-Type: application/json'));
    }
    

    public function allin_Params(array $array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }
    
    //同步通道返佣其他字段
    function company_day_commission_more(){
        fastcgi_finish_request();
        $company = DB::table('company_day_commission')->where('status', '0')->orderBy('created_at', 'asc')->limit(200)->get();
        foreach($company as $k => $v){
            $table='orders_'.date('Ymd',strtotime($v->settling_day));
            $stores = DB::table('stores')->where('store_id', $v->store_id)->first(); // 查找总店下的分店\
            $p_stores = DB::table('stores')->where('pid', $stores->id)->select('store_id')->get(); // 查找总店下的分店
            if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $v->store_id;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v->company)->where('status', 1)->select('company')->distinct()->first();
                    if(empty($pay_ways)){
                        $store_ids[] = $v1['store_id'];
                    }
                }
            }else{
                $store_ids[0] = $v->store_id;
            }
            $data = [];
            $wheres = [];
            $wheres[] = [ 'company', '=', $v->company ];
            $wheres[] = [ 'created_at', '>=', $v->settling_day . ' 00:00:00' ];
            $wheres[] = [ 'created_at', '<=', $v->settling_day . ' 23:59:59' ];
            // 优惠金额
            $data['discount_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('pay_status', '=', '1')->sum('discount_amount');
            // 优惠笔数
            $data['discount_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('pay_status', '=', '1')->where('discount_amount', '>', '0')->count('id');
            // 退款笔数
            $data['refund_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('pay_status', '=', '6')->count('id'); 
            // 微信总金额
            $data['wx_total_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '1')->sum('total_amount');
            // 微信总笔数
            $data['wx_total_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '1')->count('id');
            // 微信退款总金额
            $data['wx_refund_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '6')->sum('total_amount'); 
            // 微信退款总笔数
            $data['wx_refund_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '6')->count('id');
            // 微信方式手续费
            $data['wx_fee_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '1')->sum('fee_amount');
            // 微信优惠金额
            $data['wx_discount_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '1')->sum('discount_amount');
            // 微信优惠总笔数
            $data['wx_discount_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'weixin')->where('pay_status', '=', '1')->where('discount_amount', '>', '0')->count('id');
            // 支付宝总金额
            $data['zfb_total_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '1')->sum('total_amount');
            // 支付宝订单总笔数
            $data['zfb_total_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '1')->count('id');
            // 支付宝退款总金额
            $data['zfb_refund_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '6')->sum('total_amount');
            // 支付宝退款总笔数
            $data['zfb_refund_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '6')->count('id');
            // 支付宝方式手续费
            $data['zfb_fee_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '1')->sum('fee_amount');
            // 支付宝优惠金额
            $data['zfb_discount_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '1')->sum('discount_amount');
            // 支付宝优惠笔数
            $data['zfb_discount_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'alipay')->where('pay_status', '=', '1')->where('discount_amount', '>', '0')->count('id');
            // 云闪付总金额
            $data['un_total_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '1')->sum('total_amount');
            // 云闪付总笔数
            $data['un_total_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '1')->count('id');
            // 云闪付退款总金额
            $data['un_refund_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '6')->sum('total_amount');
            // 云闪付退款总笔数
            $data['un_refund_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '6')->count('id');
            // 云闪付手续费
            $data['un_fee_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '1')->sum('fee_amount');
            // 云闪付优惠金额
            $data['un_discount_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '1')->sum('discount_amount'); 
            // 云闪付优惠笔数
            $data['un_discount_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('pay_status', '=', '1')->where('discount_amount', '>', '0')->count('id');
            // 翼支付总金额
            $data['tel_total_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '1')->sum('total_amount');
            // 翼支付总笔数
            $data['tel_total_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '1')->count('id');
            // 翼支付退款金额
            $data['tel_refund_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '6')->sum('total_amount');
            // 翼支付退款笔数
            $data['tel_refund_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '6')->count('id');
            // 翼支付手续费
            $data['tel_fee_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '1')->sum('fee_amount');
            // 翼支付优惠金额
            $data['tel_discount_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '1')->sum('discount_amount');
            // 翼支付优惠笔数
            $data['tel_discount_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'Bestpay')->where('pay_status', '=', '1')->where('discount_amount', '>', '0')->count('id');
            // 刷卡支付金额
            $data['shuaka_amount'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('ways_type_desc', '刷卡支付')->where('pay_status', '=', '1')->sum('total_amount');
            // 刷卡支付笔数
            $data['shuaka_num'] = DB::table($table)->whereIn('store_id', $store_ids)->where($wheres)->where('ways_source', '=', 'unionpay')->where('ways_type_desc', '刷卡支付')->where('pay_status', '=', '1')->count('id');
            $data['status'] = 1;
            $res=DB::table('company_day_commission')->where('id', '=', $v->id)->update($data);
            unset($data);
            unset($store_ids);
        }
    }
    
    //每天创建新表
    public function create_database(){
        //获取前一天时间
        $time = 'orders_' . date("Ymd", strtotime("-1 day"));
        //执行原生sql语句建表
        DB::statement("CREATE TABLE `$time` (`id` int(11) NOT NULL AUTO_INCREMENT,`config_id` varchar(255) NOT NULL,`out_trade_no` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '系统订单号',`trade_no` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '无' COMMENT '支付订单号',`qwx_no` varchar(255) NOT NULL DEFAULT '',`other_no` varchar(255) NOT NULL DEFAULT '',`auth_code` varchar(255) NOT NULL DEFAULT '' COMMENT '支付条码',`store_id` varchar(255) DEFAULT NULL COMMENT '系统门店id',`out_store_id` varchar(255) NOT NULL DEFAULT '' COMMENT '第三方商户号',`is_settlement_user` varchar(255) NOT NULL DEFAULT '02' COMMENT '佣金是否结算给代理商',`user_id` int(10) NOT NULL DEFAULT '0' COMMENT '推广员id',`merchant_id` int(10) DEFAULT '0' COMMENT '系统门店收银员',`store_name` varchar(255) NOT NULL,`merchant_name` varchar(255) NOT NULL,`ways_type` int(11) DEFAULT NULL COMMENT '订单类型',`rate` decimal(10,3) NOT NULL COMMENT '交易时的费率',`ways_type_desc` varchar(255) DEFAULT NULL,`ways_source` varchar(20) NOT NULL DEFAULT 'alipay',`ways_source_desc` varchar(255) NOT NULL,`pay_method` varchar(255) NOT NULL DEFAULT 'qr_code',`company` varchar(255) NOT NULL DEFAULT '' COMMENT '通道方',`total_amount` decimal(11,2) DEFAULT NULL COMMENT '订单总金额',`receipt_amount` decimal(11,2) DEFAULT '0.00' COMMENT '商家实际收款金额',`buyer_pay_amount` decimal(10,2) NOT NULL DEFAULT '0.00',`pay_amount` decimal(10,2) NOT NULL DEFAULT '0.00',`fee_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '手续费',`shop_price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00',`shop_count` int(10) NOT NULL DEFAULT '1',`settlement_amount` decimal(10,2) NOT NULL DEFAULT '0.00',`buyer_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '买家支付宝或者微信id',`buyer_logon_id` varchar(255) NOT NULL DEFAULT '' COMMENT '支付宝账户名称或者微信呢称',`payment_method` varchar(255) DEFAULT NULL COMMENT 'credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知',`status` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'paying' COMMENT '支付状态',`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '无' COMMENT '备注信息',`pay_status` tinyint(4) DEFAULT '2' COMMENT '系统订单状态',`pay_status_desc` varchar(255) DEFAULT '等待支付',`cost_rate` decimal(10,2) DEFAULT '0.00' COMMENT '成本费率',`coupon_type` varchar(255) NOT NULL DEFAULT '0',`coupon_amount` decimal(10,2) NOT NULL DEFAULT '0.00',`refund_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '退款金额',`mdiscount_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '商家优化金额',`discount_amount` double(10,2) NOT NULL DEFAULT '0.00' COMMENT '第三方平台优惠金额',`dk_jf` int(10) NOT NULL DEFAULT '0',`dk_money` decimal(10,2) NOT NULL DEFAULT '0.00',`member_money` decimal(10,2) NOT NULL DEFAULT '0.00',`refund_no` varchar(255) NOT NULL DEFAULT '',`device_id` varchar(255) NOT NULL DEFAULT 'app',`pay_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户支付时间',`notify_url` varchar(255) NOT NULL DEFAULT '' COMMENT '异步通知地址',`created_at` timestamp NULL DEFAULT NULL,`updated_at` timestamp NULL DEFAULT NULL,`rata_money` decimal(10,2) NOT NULL DEFAULT '0.00',PRIMARY KEY (`id`),UNIQUE KEY `out_trade_no` (`out_trade_no`),KEY `company` (`company`),KEY `store_id` (`store_id`),KEY `ways_type` (`ways_type`),KEY `ways_source` (`ways_source`),KEY `pay_status` (`pay_status`),KEY `notify_url` (`notify_url`),KEY `trade_no` (`trade_no`),KEY `qwx_no` (`qwx_no`),KEY `created_at` (`created_at`),KEY `auth_code` (`auth_code`) USING BTREE,KEY `pay_time` (`pay_time`) USING BTREE,KEY `user_id` (`user_id`) USING BTREE,KEY `other_no` (`other_no`) USING BTREE,KEY `pay_method` (`pay_method`) USING BTREE,KEY `idx_storeid_wayssource_createdat` (`store_id`,`ways_source`,`created_at`),KEY `idx_storeid_wayssource_createdat_paystatus_mdiscountamount` (`store_id`,`ways_source`,`created_at`,`pay_status`,`mdiscount_amount`),KEY `idx_storeid_paystatus_updatedat` (`store_id`,`pay_status`,`updated_at`),KEY `idx_storeid_paystatus_createdat_ratamoney` (`store_id`,`pay_status`,`created_at`,`rata_money`),KEY `idx_discountamount_createdat_userid` (`discount_amount`,`created_at`,`user_id`),KEY `idx_10ba7b83e8223cf14c09a099dd816340` (`store_id`,`pay_method`,`ways_source`,`created_at`,`pay_status`,`mdiscount_amount`),KEY `idx_paystatus_createdat_userid_totalamount` (`pay_status`,`created_at`,`user_id`,`total_amount`),KEY `idx_storeid_paystatus_wayssource_createdat_feeamount` (`store_id`,`pay_status`,`ways_source`,`created_at`,`fee_amount`),KEY `idx_paystatus_updatedat_storeid` (`pay_status`,`updated_at`,`store_id`),KEY `idx_paystatus_createdat_userid_feeamount` (`pay_status`,`created_at`,`user_id`,`fee_amount`),KEY `idx_paystatus_createdat_merchantid` (`merchant_id`,`created_at`,`pay_status`),KEY `idx_storeid_userid_createdat` (`store_id`,`user_id`,`created_at`)) ENGINE=InnoDB AUTO_INCREMENT=19009521 DEFAULT CHARSET=utf8;");
    }
    
    public function move_data(){
        $table='orders_' . date("Ymd", strtotime("-1 day"));
        $date_start=date("Y-m-d 00:00:00", strtotime("-1 day"));
        $date_end=date("Y-m-d 23:59:59", strtotime("-1 day"));
        DB::statement("INSERT INTO  `$table` SELECT * FROM `orders` where `created_at`>='$date_start' and `created_at`<='$date_end';");
    }
    
        /**
     * 门店流失计划任务
     * 2022/09/09 11:34
     */
    public function store_totalmoney_zero(){
        // fastcgi_finish_request();
        //查询所有门店
        $stores = DB::table('stores')->where('pid', '=', 0)->select('store_id')->orderBy('sort','desc')->get();
        //查询日期
        $timestart = date("Y-m-d", strtotime("-1 day"));
        $where = [];
        $where[] = [ 'settling_day', '=', $timestart ];
        foreach( $stores as $k => $v ){
            $store = Db::table('stores')->where(['store_id' => $v->store_id ])->first();
            $pstore = Db::table('stores')->where(['pid' => $store->id ])->get();
            if( empty($pstore[0]->store_id) ){
                $store_ids[0] = $v->store_id;
            }else{
                $store_ids[0] = $v->store_id;
                foreach( $pstore as $key => $val ){
                    $store_ids[$key+1] = $val->store_id; // 总店 + 分店
                }
            }
            $stores_loss = DB::table('stores_loss')->where([ 'store_id' => $v->store_id ])->first(); // 门店流失记录
            if(!$stores_loss){
                DB::table('stores_loss')->insert([ 'store_id' => $v->store_id, 'user_id' => $store->user_id ]); // 门店流失记录 添加门店
                $stores_loss = DB::table('stores_loss')->where([ 'store_id' => $v->store_id ])->first(); // 门店流失记录
            }
            $store_amount = DB::table('stores_day_count')->where($where)->whereIn('store_id', $store_ids)->sum('store_amount'); // 总店 + 分店总金额
            if( $store_amount >0 ){ // 总店 + 分店无流水
                DB::table('stores_loss')->where([ 'store_id' => $v->store_id ])->update([ 'num' => 0, 'start_time' => null ]);
            }else{ // 总店 + 分店有流水
                $res=DB::table('stores_loss')->where([ 'store_id' => $v->store_id ])->update([ 'num' => $stores_loss->num + 1 ]);
                file_put_contents('b1346346.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
                file_put_contents('b1346346.log',var_export($res,true)."\r\n",FILE_APPEND);
                file_put_contents('b1346346.log',var_export($stores_loss->num + 1,true)."\r\n",FILE_APPEND);
                if( !$stores_loss->start_time ){ // 首次门店流失
                    DB::table('stores_loss')->where([ 'store_id' => $v->store_id ])->update([ 'start_time' => $timestart ]);
                }
            }
            unset($store_ids);
        }
    }
    
    public function stop_stores(){
        fastcgi_finish_request();
        //查询所有门店
        $stores = DB::table('stores_close')->get();
        $stores=json_decode($stores,true);
        foreach ($stores as $k=>$v){
            $gt_store=DB::table('stores')->where('store_id',$v['store_id'])->first();
            if($gt_store->store_money>0){
                DB::table('stores_close')->where('id',$v['id'])->delete();
            }else{
                DB::table('stores')->where('store_id',$v['store_id'])->update(array('state'=>'3'));
                DB::table('stores_close')->where('id',$v['id'])->delete();
            }
        }
        //查询日期
    }

    public function curl_merch($url,$method,$params,$header = []){
        //初始化CURL句柄
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($header)){
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header);
        }
        //请求时间
        $timeout = 30;
        curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        switch ($method){
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                if(is_array($params)){
                    $params = json_encode($params,320);
                }

                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($curl, CURLOPT_POSTFIELDS,$params);
                break;
        }
        $data = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);//关闭cURL会话

        return $data;
    }
    
    public function youpaycallback(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            file_put_contents('youpaycallback.log',var_export($data,true)."\r\n",FILE_APPEND);
            $data = json_decode($data, true);
            if (isset($data['orgReqTraceId'])&&$data['txnSta']=='03') {
                $out_trade_no = $data['orgReqTraceId'];
                $order = Order::where('out_trade_no', $out_trade_no)->first();

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['orderNo']) ? $data['orderNo'] : $out_trade_no;
                        $pay_time = date('Y-m-d H:i:s', time());
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = isset($data['buyerId']) ? $data['buyerId'] : "";

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount
                        ];
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data1 = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '26001',//返佣来源
                                'source_desc' => '邮储银行',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data1);
                        }
                    }
                }
            }
            

            return json_encode([
                'respCd' => '0000',
                'respDesc' => "回调成功",
                'otherTraceID' => $trade_no,
                'otherReqDate' => date('H:i:s',time()),
            ]);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }
}
